Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29107

Combine two observables with one being optional

I have two observables which I need to combine.

observA: | ----- A B C D E ---------------------------F G H------>
observB: | ------------------X ---------------X-------------X---->
         =========================================================
result:  |-------------------A----------------<NULL>--------F---->

             |---- part A ----|         |- part B --|

Part A or any part will happen within a 100ms window. The time between the parts is much bigger. In words: If observB emits an item, it should continue with or without a value of observB But if observA emits, it should wait for observB

So, what I have so far is only a solution for part A

| ----- A B C D E -------->
| ------------------X ---->
===========zip===============
|-------------------A----->


Observable.zip(
    observA$.throttle(100),
    observB$, (a, b => a)
   .subscribe(...)

which doesn't work for part B because it will wait for observA. I'm not sure how to solve this with RxJS, so any help would be. Maybe I shouldn't do this with RxJs only. Any help would be appreciated

UPDATE: Solution, thanks to @martin

Upvotes: 1

Views: 193

Answers (1)

martin
martin

Reputation: 96891

Sounds like you could use something along these lines:

Observable.defer(() => {
    return observA$.withLatestFrom(observB$.take(1).startWith(null), v => v)
  })
  .take(1)
  .repeat()
  .subscribe(...);

It takes always the first value from observB$ and then waits until an emission observA$. Then it repeats this process with take(1).repeat().

Upvotes: 1

Related Questions