简体   繁体   中英

RxSwift Use withLatestFrom operator with multiple sources

I have 3 observables namely source, source1 and source2. What I want is whenever source emits distinct event get the value of source1 and source2. This is the code I've come up with, obviously it won't compile since withLatestFrom expects only one observable.

source.distinctUntilChanged()
        .withLatestFrom(source1, source2) { ($0, $1.0, $1.1) }
        .subscribe(onNext: { (A, B, C) in
            print("OnNext called")
        })
        .disposed(by: bag)

You almost have it. How about just combining source1 and source2 ?

source.distinctUntilChanged()
    .withLatestFrom(Observable.combineLatest(source1, source2)) { ($0, $1.0, $1.1) }
    .subscribe(onNext: { (A, B, C) in
        print("OnNext called")
    })
    .disposed(by: bag)

You can do something like this

        let source = PublishSubject<Int>()
        let source1 = PublishSubject<Int>()
        let source2 = PublishSubject<Int>()

        Observable
            .combineLatest([source,source1,source2])
            .distinctUntilChanged { (oldArray, newArray) -> Bool in
                return oldArray.first == newArray.first
            }
            .subscribe(onNext: { (values) in
                debugPrint("source1 value is \(values[1]) and source2 value is \(values[2])")
            })
            .disposed(by: self.disposeBag)

        source1.onNext(100)
        source2.onNext(200)
        source.onNext(3)

        source.onNext(4)
        source.onNext(4)

O/P will look like 在此处输入图像描述

Catch:

I am using combineLatest that means this will work only after all the observables emitted values at least once. You can always use startWith operator to ensure all your observables emits value at least once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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