Bart van den Burg
Bart van den Burg

Reputation: 2344

Get values from two streams whenever one emits

I have two observable streams, let's say:

const stream1 = from([1,2,3]);
const stream2 = from([4,5,6]);

now I want to do something when either of those two emits, and when they do, I don't care about the latest value from the other (so combineLatest doesn't cut it here). I want my subscribe function be called 6 times, once for each value of both observables. E.g. (assuming they don't emit all values at once, but at random intervals):

1, 4, 2, 5, 3, 6

How do I set this up?

Upvotes: 1

Views: 880

Answers (2)

customcommander
customcommander

Reputation: 18901

I think you want to merge your streams:

const stream1$ = new Observable(subscriber => {
  setTimeout(() => { subscriber.next(1); }, 150);
  setTimeout(() => { subscriber.next(2); }, 250);
  setTimeout(() => { subscriber.next(3); subscriber.complete(); }, 350);
});

const stream2$ = new Observable(subscriber => {
  setTimeout(() => { subscriber.next(4); }, 200);
  setTimeout(() => { subscriber.next(5); }, 300);
  setTimeout(() => { subscriber.next(6); subscriber.complete(); }, 400);
});

merge(stream1$, stream2$).subscribe(n => console.log(`n=${n}`));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.2.0/rxjs.umd.min.js"></script>
<script>const {Observable, merge} = rxjs;</script>

Upvotes: 1

Anand Tiwari
Anand Tiwari

Reputation: 29

Did you look at the merge operator? I think in your case it will be the best fit. I have used it for subscribing to pagination and sorting events simultaneously, both events are emitted at different times. Few methods for merge have been deprecated but you can mergeWith in place of them. Below is the documentation of both. https://rxjs-dev.firebaseapp.com/api/operators/merge, https://rxjs-dev.firebaseapp.com/api/operators/mergeWith

Upvotes: 1

Related Questions