Performance: combineLatest and forkJoin for combining
This affects how multiple asynchronous data streams are combined and how quickly the UI updates with combined results.
combineLatest([obs1, obs2, obs3]).subscribe(results => { /* update UI reactively */ });forkJoin([obs1, obs2, obs3]).subscribe(results => { /* update UI */ });| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| combineLatest | Multiple updates on each emission | Multiple reflows if UI changes | Higher paint cost due to frequent updates | [OK] |
| forkJoin | Single update after all complete | Single reflow | Lower paint cost with one update | [OK] Good |
combineLatest and forkJoin in Angular RxJS?combineLatest behaviorcombineLatest emits a new combined value whenever any source observable emits after all have emitted at least once.forkJoin behaviorforkJoin waits for all source observables to complete and then emits a single combined array of their last emitted values.combineLatest emits on any change; forkJoin emits once after all complete. -> Option CcombineLatest and forkJoin from RxJS in Angular?combineLatest and forkJoin are exported from the main 'rxjs' package, not from Angular core or operators.@angular/core is Angular framework code, rxjs/operators contains operators like map, filter, but not these combinators.import { of, combineLatest } from 'rxjs';
const obs1 = of(1, 2);
const obs2 = of('A', 'B');
combineLatest([obs1, obs2]).subscribe(console.log);of observables emitting synchronouslyobs1 and obs2 emit their values immediately and complete. obs1 emits 1 then 2; obs2 emits 'A' then 'B'.combineLatest with synchronous emissionscombineLatest waits for all to emit at least once, then emits combined latest values on any emission. Since subscriptions are synchronous, obs1 emits both values first (latest from obs1 is 2), then obs2 emits 'A' (triggers [2, 'A']), then 'B' (triggers [2, 'B']).forkJoin:
import { forkJoin, of } from 'rxjs';
const obs1 = of(1, 2);
const obs2 = of('A', 'B');
forkJoin([obs1, obs2]).subscribe(console.log);forkJoin accepts an array of observables and waits for all to complete, then emits an array of their last emitted values.getUser() and getOrders(). You want to display user info immediately and update orders live as they change. Which combination should you use?getUser() usually emit once and complete. Orders may update live, so getOrders() is likely a stream emitting multiple times.forkJoin for getUser() to wait for the single response. Use combineLatest for getOrders() to get live updates. Then combine these appropriately (e.g., nest or switchMap) to show user info immediately and update orders live.Pass the test and this pattern moves unknown