Search code examples
javascriptrxjsrxjs5reactivex

Wait and accumulate values until other observable fires


I have two observables and I want just one value from each. In case the observable2 pushes a value first I would like to wait and keep the received value until observable1 pushes a value and push kept value then. Basicaly the same behaviour as with skipUntil with the difference that I don't want to discard the value. I guess it I could do it by concatting the observables but I would like to keep them separate.

observable1
  .take(1)
  .subscribe(doSomething)

observable2
  .take(1)
  // .skipUntil(observable1)
  .waitUntil(observable1) // Something like this
  .subscribe(doSomethingElse)

Solution

  • This will wait for observable1 to push and then switches to observable2:

    observable1.switchMap(() => observable2)
               .take(1)
               .subscribe(doSomethingElse);
    

    If you want observable1 to only fire once (for example if you subscribe to it somewhere else like in your example), consider using .share().