forkJoin is an RxJS operator (a creation function) that runs several Observables in parallel and emits once, when all of them have completed, with the last value from each. It is similar to Promise.all. Typical use in Angular — load several independent API calls before showing a page: loadDashboard() { forkJoin({ user: this.api.getUser(), orders: this.api.getRecentOrders(), stats: this.api.getStats() }).subscribe(({ user, orders, stats }) => { this.user = user; this.orders = orders; this.stats = stats; }); } The three HTTP requests run at the same time, and the subscriber receives one object with all results. The total wait is roughly the slowest request, not the sum. Important behaviour - It waits for completion. HTTP observables complete after one response, so they are ideal. Observables that never complete (BehaviorSubject, interval, valueChanges) will make forkJoin never emit — use combineLatest instead for ongoing streams. - If any source errors, forkJoin errors immediately and the other results are lost. Handle errors per request when partial results are acceptable: forkJoin({ user: this.api.getUser(), orders: this.api.getRecentOrders().pipe(catchError(() => of([]))) }) - If a source completes without emitting any value, forkJoin completes without emitting. Comparison with related operators - combineLatest: emits whenever any source emits (after all have emitted at least once). For live, changing values such as filters. - zip: pairs values by index. - concat / concatMap: run in sequence when order or dependency matters. - switchMap / mergeMap: when one request depends on the result of another. In signal-based code, you can convert the result with toSignal(forkJoin(...)).
Ravindra Wadile · · 0 likes