使用Rx扫描运算符将数据流转化为价值

时间:2018-08-28 21:38:27

标签: javascript typescript rxjs rxjs6

我有一个来自实时数据源的位置数据流,我正在尝试使用rx scan运算符来减少该流,并计算出新的位置变化时的行进距离。

发出的值采用这种格式

{
  lat: 3.4646343,
  lng: 6.4343234,
  speed: 1.3353,
  heading: 279
}

这是处理器

function distanceBetweenPoints (point, point2, unit: string = 'M') {
    const radlat1 = Math.PI * (point.lat / 180);
    const radlat2 = Math.PI * (point2.lat / 180);
    const theta = point.lng - point2.lng;
    const radtheta = Math.PI * theta / 180;
    let dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
    dist = Math.acos(dist);
    dist = dist * 180 / Math.PI;
    dist = dist * 60 * 1.1515;

    if (unit == 'KM') { dist = dist * 1.609344; }
    if (unit == 'M') { dist = dist * 1.609344 * 1000; }
    return dist;
}

const location$: Subject<LocationUpdate> = new Subject();

location$
    .pipe(
        map(location => {
            return { lat: location.lat, lng: location.lng };
        }),
        scan((x, y) => {
            return distanceBetweenPoints(x, y);
        }),
        takeUntil(locationUpdateEnd$)
    )
    .subscribe(distance => console.info('distance', distance));

我很确定我使用scan运算符是错误的,因为我在输出中看到Nan和一个数值。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

使用pairwise()代替scan()

pairwise()将发出一对值:[last_value, current_value],在您的情况下为[last_location, current_location]

然后map()到您的距离函数。

答案 1 :(得分:0)

我使用了pairwise运算符

location$
        .pipe(
            map(coords => {
                return { lat: coords.lat, lng: coords.lng };
            }),
            pairwise(),
            scan((acc, coords) => {
                return acc + distanceBetweenPoints(coords[0], coords[1]);
            }, 0),
            takeUntil(endtrip$)
        )
        .subscribe(console.log);