Search code examples
iosswiftrx-swiftreactivecombine

RxSwift Use withLatestFrom operator with multiple sources


I have 3 observables, namely source, source1 and source2. What I want is whenever source emits a distinct event to 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)

Solution

  • 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)