Reputation: 2062
I have an array of observables a$, b$, c$, d$
. I want them them to run in sequence. E.g. if a$
finishes, then b$
. If b$
finishes then $c
...
I know forkJoin([a$, b$, c$, d$])
except that it will do this in parallel. Is there a corresponding operator? Or can I tell forkJoin
to run in sequence?
Upvotes: 1
Views: 4492
Reputation: 20063
You can use concat
to run them in sequence:
concat(a$, b$, c$).subscribe(console.log);
If you also want to skip any intermediate emissions from the source observables on the resulting observer, you can use something like
concat(...[a$, b$, c$].map(source$ => source$.pipe(last())));
… or if you want to only collect the last emission of each source observable into a single emission like forkJoin
, you attach toArray
to it:
concat(...[a$, b$, c$].map(source$ => source$.pipe(last()))).pipe(
toArray(),
);
Of course you could extract this into your own operator now if you want:
const concatLast = <T>(...sources: Observable<T>) => concat(
...sources.map(source$ => source$.pipe(last()))
).pipe(
toArray(),
);
There are still fine differences to forkJoin
in how it behaves when one of the source observables completes without emitting.
On the rxjs website there's a useful tool called the operator decision tree which helps you figure out the appropriate operator, for example in this case
Upvotes: 7