how to use the forkjoin function from the rxjs library in typescript

To use the forkJoin function from the RxJS library in TypeScript, you first need to import it:

import { forkJoin } from 'rxjs';
33 chars
2 lines

forkJoin is a creation operator that takes an array of observables and combines them into a single observable that emits an array of values from each of the source observables when they all complete.

Here's an example of how to use forkJoin:

import { forkJoin, of } from 'rxjs';
import { delay } from 'rxjs/operators';

const observable1$ = of(1).pipe(delay(1000)); // emits 1 after 1 second
const observable2$ = of(2).pipe(delay(2000)); // emits 2 after 2 seconds
const observable3$ = of(3).pipe(delay(3000)); // emits 3 after 3 seconds

forkJoin([observable1$, observable2$, observable3$]).subscribe(
    ([value1, value2, value3]) => {
        console.log(`Values: ${value1}, ${value2}, ${value3}`);
    (error) => {
        console.log(`Error: ${error}`);
    () => {
588 chars
19 lines

In this example, we create three observables that emit a value after a certain delay using the of operator and the delay operator from RxJS. Then we pass an array of these observables to forkJoin and subscribe to the resulting observable.

When all three source observables complete, forkJoin emits an array of their values, which we destructure in the subscription callback using ES6 destructuring syntax. We use console.log to print the values and "Completed!" to indicate that the observable has completed.

Note that forkJoin waits for all source observables to complete before emitting their values, so if any observable in the array throws an error, the entire observable chain will fail and the error callback will be called.

gistlibby LogSnag