Lessons31. forkJoin: wait for every task to finish
Lessons · 31
31. forkJoin: wait for every task to finish
forkJoin — the RxJS counterpart of Promise.all
If you know Promise.all, this is the closest concept. forkJoin([a$, b$, c$]) subscribes to every source, waits until each one completes, and then hands back an array of their last values in a single signal.
forkJoin([assets$, profile$])
// after both complete → next(['Assets OK', 'Profile OK']) → complete()
When to use it
When you have several independent HTTP requests and the UI should appear only after all of them arrive. For example: load the profile + load permissions + load settings.
The main danger
If even one source never completes (an interval, say), forkJoin waits forever. It only suits finite Observables.
Your task
- The subscription receives the array
[assets, profile]. Destructure it right in the subscription parameter:([assets, profile]) => .... - Inside, do
values.push('Ready: ' + assets + ', ' + profile).
Deterministic check
This task's check runs in TestScheduler virtual time. If your solution is right, the console shows only Test Passed!. Don't add extra console.logs, or the check will fail.
Solution spoiler · click to reveal
const { timer, forkJoin, map } = Rx;
const assets$ = timer(10).pipe(map(() => 'Assets OK'));
const profile$ = timer(20).pipe(map(() => 'Profile OK'));
const ready$ = forkJoin([assets$, profile$]);
ready$.subscribe(([assets, profile]) => {
values.push('Ready: ' + assets + ', ' + profile);
}); script.ts
CONSOLE · Console output
Hit Run to see the result...