I have a sequence of observables that need to be executed in order, but I want to keep them cold (without subscribing) so that further chaining is possible.
const tasks = [observable1, observable2, observable3];
If I return concat(...tasks)
and then try to chain from it
tasks$.pipe(switchMap(() => ...))
, the switchMap will run for each observable inside concat - 3 times.
I am searching for a solution similar to forkJoin where
forkJoin(...tasks).pipe(switchMap(() => ...))
in which the switchMap will only execute once. However, using forkJoin alone won't work since the order should also be maintained.
The options I've explored so far are:
- Return
forkJoin(concat(...tasks))
. This technically works because forkJoin waits for concat to complete, but it feels inefficient since forkJoin is designed to handle multiple observables, not just one. - Return
concat(...tasks).pipe(toArray())
. This might be better than forkJoin but still doesn't feel like the most efficient solution. Another option istakeLast()
which serves a similar purpose but implies an emphasis on the last value rather than completion. Something like finalize() would be ideal, but with the ability to emit in order to block the stream when needed.
(Check out Stackblitz examples here)
Is there a more suitable operator for waiting for concat to finish or a better alternative to concat altogether that maintains the order of execution and allows for seamless chaining like forkJoin? It seems like there should be a basic operator that simply waits for a source observable to complete and then emits the result, considering the availability of operators like forkJoin for handling multiple observables and maintaining their order.