These tools help you work with many streams of data at once. They let you wait for multiple things to happen and then act on all results together.
combineLatest and forkJoin for combining in Angular
combineLatest([observable1, observable2, ...]) forkJoin([observable1, observable2, ...])
combineLatest emits new values whenever any input changes, but only after all have emitted at least once.
forkJoin waits for all inputs to complete, then emits the last value from each.
combineLatest([obs1, obs2]).subscribe(([val1, val2]) => {
console.log(val1, val2);
});forkJoin([obs1, obs2]).subscribe(([val1, val2]) => {
console.log(val1, val2);
});This Angular component shows how combineLatest updates whenever either observable emits, after both have emitted once. It also shows how forkJoin waits for both observables to finish and then emits their last values.
import { Component } from '@angular/core'; import { of, interval, combineLatest, forkJoin } from 'rxjs'; import { take, map } from 'rxjs/operators'; @Component({ selector: 'app-combine-example', template: ` <h2>combineLatest Output:</h2> <pre>{{ combineLatestOutput }}</pre> <h2>forkJoin Output:</h2> <pre>{{ forkJoinOutput }}</pre> ` }) export class CombineExampleComponent { combineLatestOutput = ''; forkJoinOutput = ''; constructor() { const obs1 = interval(1000).pipe( take(3), map(i => `A${i + 1}`) ); const obs2 = interval(1500).pipe( take(2), map(i => `B${i + 1}`) ); combineLatest([obs1, obs2]).subscribe(([val1, val2]) => { this.combineLatestOutput += `${val1} & ${val2}\n`; }); forkJoin([obs1, obs2]).subscribe(([val1, val2]) => { this.forkJoinOutput = `${val1} & ${val2}`; }); } }
combineLatest needs all observables to emit at least once before it starts emitting.
forkJoin only emits once, after all observables complete.
If any observable in forkJoin never completes, it will never emit.
combineLatest combines latest values and updates on any change.
forkJoin waits for all to finish and emits once.
Use combineLatest for live updates, forkJoin for final results.