Back to course

Combining Observables: forkJoin and combineLatest

The Complete Angular Developer: From Zero to Hero

56. Combining Observables: forkJoin and combineLatest

Many application features require retrieving data from multiple endpoints or sources simultaneously. RxJS offers various combinator functions to merge data streams.

1. forkJoin (Wait for All to Complete)

forkJoin is analogous to Promise.all(). It takes an array of Observables and waits for every single one to complete. Once they all complete, it emits a single array (or object) containing the last value from each source Observable, and then completes itself.

Use Case: Fetching multiple, independent pieces of data required simultaneously (e.g., getting User data and Settings data on page load).

typescript import { forkJoin, of } from 'rxjs';

const user$ = this.http.get('/api/user/1'); const permissions$ = this.http.get('/api/permissions');

forkJoin([user$, permissions$]).subscribe( ([userData, permissionData]) => { console.log('All data loaded:', userData, permissionData); // Initialize application state } );

2. combineLatest (React to Any Change)

combineLatest takes multiple Observables and emits a new value whenever any of the source Observables emits a value. The emitted value is an array or object containing the latest value from every source Observable.

Use Case: Real-time updates based on two or more dependent sources (e.g., filtering a list based on an input stream AND a dropdown selection stream).

typescript import { combineLatest, timer } from 'rxjs';

const timerOne$ = timer(1000, 4000); // emits 0, 1, 2, ... const timerTwo$ = timer(2000, 4000); // emits 0, 1, 2, ...

combineLatest([timerOne$, timerTwo$]).subscribe( ([t1, t2]) => { console.log(T1: ${t1}, T2: ${t2}); } );

/* Output sequence example: (waits 2s) T1: 0, T2: 0 (at 4s) T1: 1, T2: 0 (at 6s) T1: 1, T2: 1 */

Key difference: forkJoin completes after one emission; combineLatest stays active and keeps emitting.