Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS: merge with single emit on completion

Tags:

rxjs

Is there an RxJS factory function (or more generally a pattern) to merge several others together, but only emit once when all of them have completed?

The use case I want this for, is to wait for several parallel operations, and then do something else, once they complete. For promises this can be done like this:

Promise.all(A, B, C).then(() => console.log('done'));

For observables, the best I've come up with yet is

merge(A, B, C).pipe(takeLatest(1)).subscribe(() => console.log('done'));

This doesn't account for A, B, and C being empty, though. And it doesn't provide a deterministic value to the subscriber. Isn't there a simple built-in solution for this use-case?

like image 430
kremerd Avatar asked Sep 06 '25 13:09

kremerd


1 Answers

You can use forkJoin. This operator emits once all its given observables are completed.

const { Observable, of, forkJoin } = rxjs;

const obs1$ = new Observable(subscriber => {
  subscriber.next('obs1$ - value 1');
  subscriber.next('obs1$ - value 2');
  subscriber.complete();
})
const obs2$ = of('obs2$');
const obs3$ = of('obs3$');

const result$ = forkJoin(
  obs1$,
  obs2$,
  obs3$
);

result$.subscribe(v => console.log(v));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>
like image 89
Jonathan Stellwag Avatar answered Sep 09 '25 18:09

Jonathan Stellwag