[英]How to observe previous and current value in RxSwift for UITableView tap/selection?
[英]Observe an observable every 60 second and compare to its previous value in RxSwift
我想做的是:
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)
您要求的是在設備超過一定速度時發出一個值,該值實際上是在位置 object 中提供的值。 就用它。
extension CLLocationManager {
func goingFast(threshold: CLLocationSpeed) -> Observable<CLLocation> {
return rx.didUpdateLocations
.compactMap { $0.last }
.filter { $0.speed > threshold }
}
}
有了上述內容,如果您想知道設備在過去 60 秒內的任何時間點是否超過 10 m/s,您可以使用 Alexander 在評論中提到的sample
:
let manager = CLLocationManager()
let fast = manager.goingFast(threshold: 0.167)
.sample(Observable<Int>.interval(.seconds(60), scheduler: MainScheduler.instance))
也就是說,作為跟蹤幅度增加的一般情況,您需要使用scan
運算符。
extension CLLocationManager {
func example(period: RxTimeInterval, threshold: Double, scheduler: SchedulerType) -> Observable<CLLocation> {
return rx.didUpdateLocations
.compactMap { $0.last }
.sample(Observable<Int>.interval(period, scheduler: scheduler))
.scan((CLLocation?.none, false)) { last, current in
if (last.0?.distance(from: current).magnitude ?? 0) < threshold {
return (current, false)
}
else {
return (current, true)
}
}
.filter { $0.1 }
.compactMap { $0.0 }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.