Search code examples
javascriptreactive-programmingrxjsobservablefrp

Conditionally combining two observables


Need to combine the following two observables:

  • observable1 emits { x: value1 }
  • observable2 emits { y: value2 }

into observable3 that emits:

  • { x: value1, y: value2 } when observable1 fires (value2 is the last value emitted by observable2)
  • { y: value } when observable2 fires

In other words, it should behave like combineLatest for observable1 emits and like merge for observable2 emits.

Is there an elegant-ish way to do this?


Solution

  • You could do :

    observable3 = Rx.Observable.merge(observable1.withLatestFrom(observable2), observable2)
    

    Note that combineLatest would not work here, as it would wait for observable2 to produce a value. withLatestFrom is taken the latest value from observable2 without the wait.

    I also recommend you to test for the edge cases :

    • observable2 has not emitted any value yet (withLatestFrom might block and wait, it is not clear from the documentation)
    • observable2 has completed prior to your creating observable3