[英]Which RxSwift operator to use for uniquely emitted elements and how to?
location.filter({$0.speed < 25})
.debounce(.seconds(20), scheduler: MainScheduler.instance)
.subscribe(onNext: { (location) in
print(location)
}).disposed(by: disposeBag)
目標:
25 for 20 seconds
保持在25 for 20 seconds
以下25 for 20 seconds
則打印位置within 20
秒內速度above 25
取消發出的事件below 25
40 秒內保持below 25
以下,則位置應在 20 秒時打印兩次,在 40 秒時再次打印。 當前的問題是:如果速度低於 25 並且在 20 秒內 observable 收到速度低於 25 的第二個事件,它會因為debounce
而取消前一個事件。
您應該添加 distinctUntilChanged 運算符:
location.distinctUntilChanged { $0.speed < 25 && $1.speed < 25 }
.debounce(.seconds(20), scheduler: MainScheduler.instance)
.filter { $0.speed < 25 }
.subscribe(onNext: { location in
print(location)
})
.disposed(by: disposeBag)
編輯如果速度小於 25,應每 20 秒打印一次位置的情況:
let isSpeedBelow = location
.distinctUntilChanged { $0.speed < 25 && $1.speed < 25 }
.flatMapLatest { location -> Observable<Double> in
if location.speed >= 25 {
return Observable.just(location)
}
return Observable<Int>.timer(.seconds(10), period: nil, scheduler: MainScheduler.instance)
.map { _ in location.speed }
}
.map { $0 < 25 }
.startWith(true)
Observable<Int>.timer(.seconds(10), period: .seconds(10), scheduler: MainScheduler.instance)
.withLatestFrom(isSpeedBelow)
.filter { $0 }
.withLatestFrom(location)
.subscribe(onNext: { location in
print(location)
})
.disposed(by: disposeBag)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.