0
0
Angularframework~5 mins

combineLatest and forkJoin for combining in Angular

Choose your learning style9 modes available
Introduction

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.

You want to update your app when any of several data sources change.
You need to wait until all data sources have sent their last value before continuing.
You want to combine user inputs from different fields and react when any input changes.
You want to load multiple API calls and proceed only when all have finished.
You want to merge live data streams and show the latest combined info.
Syntax
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.

Examples
This logs the latest values from both observables whenever either changes.
Angular
combineLatest([obs1, obs2]).subscribe(([val1, val2]) => {
  console.log(val1, val2);
});
This logs values only once, after both observables complete.
Angular
forkJoin([obs1, obs2]).subscribe(([val1, val2]) => {
  console.log(val1, val2);
});
Sample Program

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.

Angular
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}`;
    });
  }
}
OutputSuccess
Important Notes

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.

Summary

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.