DEV Community

Blake Lamb
Blake Lamb

Posted on • Updated on

How to use the 'forkJoin' RxJS operator

Overview

There are times where you will want one observable stream, that contains data from multiple observable sources. This can be accomplished by utilizing the forkJoin RxJs operator to combine multiple observable streams into one.

Getting Into It

Open an app to the component that needs to have the observables combined, or create a sandbox Angular app. Knowing what an observable is and how to create/use them is necessary to use forkJoin. If observables are a new concept, do some research about that first.

For this example I'm going to use a StackBlitz and calling the PokeApi for my observables. In the component create an array of the HTTP calls, but don't subscribe to each observable. That should look something like the example below:

// app.component.ts

export class AppComponent implements OnInit {
  private pokeApiBaseUrl = "https://pokeapi.co/api/v2";
  public pokeData$: Observable<any>;

  constructor(private _http: HttpClient) {}

  ngOnInit() {
    const pokemonData = [
      this._http.get(`${this.pokeApiBaseUrl}/pokemon`),
      this._http.get(`${this.pokeApiBaseUrl}/type`),
      this._http.get(`${this.pokeApiBaseUrl}/generation`),
    ];
    this.pokeData$ = forkJoin(pokemonData).pipe(
      tap((pokeData) => console.log({ pokeData }))
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

As you can see, the 'pokemonData' array is created with three observables by creating an HTTP call for each one. Then when the array is passed into forkJoin, each HTTP call is made in order and the three calls are compiled into one observable. This resulting observable can be seen by tapping into the pipeline like I do above.
** Note, the observable will not resolve until all http calls have been completed in the input array into forkJoin. This could be useful when trying to do something in order **

Once the pokemonData array is passed into forkJoin, you can treat it as a normal observable. As you can see above, I tap into the pipeline and console.log the result. First though you must make sure to subscribe to the forkJoin. In this example I do so by using the async pipe, but this can also be done by using .subscribe(). Another good thing to know about this operator is that the resulting Observable will always be an array, and the order of the array will always be in the same order as when you passed them in to the forkJoin.

Wrap Up

This can be a very valuable RxJS operator to utilize. Often times having code execute in order, or to be able to combine all the observables into one observable, can be extremely useful. In those situations forkJoin is a great way to accomplish that.

For a live example of the above code, see this StackBlitz

Top comments (0)