Rxjs: Observable.combineLatest vs Observable.forkJoin

Not only does forkJoin require all input observables to be completed, but it also returns an observable that produces a single value that is an array of the last values produced by the input observables. In other words, it waits until the last input observable completes, and then produces a single value and completes.

In contrast, combineLatest returns an Observable that produces a new value every time the input observables do, once all input observables have produced at least one value. This means it could have infinite values and may not complete. It also means that the input observables don't have to complete before producing a value.


combineLatest(...)

runs observables in parallel, emitting a value each time an observable emits a value after all observables have emitted at least one value.

combineLatest example

forkJoin(...)

runs observables in parallel, and emits a single value once all observables have completed.

forkJoin example

Consideration for error handling:

If any of the observables error out - with combineLatest it will emit up to the point the error is thrown. forkJoin will just give back an error if any of the observables error out.


Advanced note: CombineLatest doesn't just get a single value for each source and move onto the next. If you need to ensure you only get the 'next available item' for each source observable you can add .pipe(take(1)) to the source observable as you add it to the input array.


forkJoin - When all observables complete, emit the last emitted value from each.

combineLatest - When any observable emits a value, emit the latest value from each.

Usage is pretty similar, but you shouldn't forget to unsubscribe from combineLatest unlike forkJoin.

Tags:

Rxjs

Rxjs5