每60秒观察一次可观察到的结果,并将其与RxSwift中的先前值进行比较

问题描述 投票:1回答:1

我想做的是:

  • 每60秒观察一次location观测值,并与〜60秒前发出的事件进行比较,比较距离是否超过阈值

$0中发生了什么,我总是收到第一个发出的事件,它不是每60秒更新一次。 $ 1不过具有最近发出的事件。

这里是代码:

Observable<Int>.timer(.seconds(0), period: .seconds(60), scheduler: MainScheduler.instance)
            .withLatestFrom(location)
            .distinctUntilChanged { $0.distance(from: $1).magnitude < 10.0 }
            .subscribe(onNext: { (location) in
                print(location)
            })
            .disposed(by: disposeBag)
ios swift reactive-programming core-location rx-swift
1个回答
0
投票
您要的是在设备超过一定速度时发出一个值,该值是位置对象中实际提供的值。只需使用它。

extension CLLocationManager { func goingFast(threshold: CLLocationSpeed) -> Observable<CLLocation> { return rx.didUpdateLocations .compactMap { $0.last } .filter { $0.speed > threshold } } }

也就是说,作为跟踪幅度增加的一般情况,您需要使用scan运算符。

extension ObservableType where Element == Int { func example(threshold: Int) -> Observable<Int> { return scan((0, false)) { last, current in if current > last.0 + threshold { return (current, true) } else { return (current, false) } } .filter { $0.1 } .map { $0.0 } } }

© www.soinside.com 2019 - 2024. All rights reserved.