简体   繁体   English

哪个 RxSwift 运算符用于唯一发出的元素以及如何使用?

[英]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:目标:

  1. If the speed property remains below 25 for 20 seconds then print location如果速度属性在25 for 20 seconds保持在25 for 20 seconds以下25 for 20 seconds则打印位置
  2. If within 20 seconds speed goes above 25 cancel the emitted event如果within 20秒内速度above 25取消发出的事件
  3. If the speed remains 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM