Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 286
Konstantin K Avatar asked May 31 '26 19:05

Konstantin K


1 Answers

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
like image 105
user3743222 Avatar answered Jun 04 '26 11:06

user3743222



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!