RxSwift Use withLatestFrom operator with multiple sources

Viewed 1696

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)
2 Answers

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 enter image description here

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.

Related