Home > database >  How to trigger an observable when another observable fires in RxSwift?
How to trigger an observable when another observable fires in RxSwift?

Time:10-27

I have the following observable:

observable1
    .withLatestFrom(observable2) { (obs1Value, obj2Value) -> [SomeDataType] in
        return obj1Value.someFunction(for: obj2Value)
    }
    .bind(to: someSubject)
    .disposed(by: disposeBag)

And it should be updated when the following PublishRelay fires:

let publishRelay = PublishRelay<AnotherDataType>()

observable1 and observable2 have 2 different types

I've tried the following:

Observable.combineLatest(observable1, observable2, publishRelay.asObservable())
        .map { obs1Value, obj2Value, _ in
            return obj1Value.someFunction(for: obj2Value)
        }
        .bind(to: someSubject)
        .disposed(by: disposeBag)

But have faced the problem that observable1 & observable2 are not being binded until publishRelay fires (it basically waits for all 3 values to arrive)

I need to the observables to go through even without PublishRelay but get an extra update when the PublishRelay fires (I'm not using any data from PublishRelay inside of the observables subscription)

What's the best way to achieve the above? Thanks!

CodePudding user response:

The key here is to use startWith in order to "pre-fire" the offending observable so it has a latest value to work with. Since you don't care about the relay's value, you can map to unit and startWith unit.

It would look something like this:

Observable.combineLatest(observable1, publishRelay.asObservable().map { _ in () }.startWith(()))
    .withLatestFrom(observable2) { $0.0.someFunction(for: $1) }
    .bind(to: someSubject)
    .disposed(by: disposeBag)
  • Related