[英]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)
Goals:目标:
25 for 20 seconds
then print location25 for 20 seconds
保持在25 for 20 seconds
以下25 for 20 seconds
则打印位置within 20
seconds speed goes above 25
cancel the emitted eventwithin 20
秒内速度above 25
取消发出的事件below 25
for 40 seconds, location should be printed twice once at 20 seconds and again at 40 seconds.below 25
40 秒内保持below 25
以下,则位置应在 20 秒时打印两次,在 40 秒时再次打印。 Current problem is : If the speed goes below 25 and within 20 seconds observable receives a second event with speed below 25 it cancels out the previous event because of debounce
.当前的问题是:如果速度低于 25 并且在 20 秒内 observable 收到速度低于 25 的第二个事件,它会因为
debounce
而取消前一个事件。
You should add the distinctUntilChanged operator:您应该添加 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)
EDIT Case when location should be printed every 20 seconds if speed is less than 25:编辑如果速度小于 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.