簡體   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)

目標:

  1. 如果速度屬性在25 for 20 seconds保持在25 for 20 seconds以下25 for 20 seconds則打印位置
  2. 如果within 20秒內速度above 25取消發出的事件
  3. 如果速度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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM