RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.

This library offers us a lot of operators.One such operators are forkJoin and combineLatest.

forkJoin

forkJoin is a special operator from RxJx that let’s you combine / accept multiple ObservableInputs and returns the objects of values with exact shape of input.

let us imagine such a situation : We have a scenario to fetch multiple API’s response and load the data based on all responses.

one way to solve this will be by calling all the api’s one by one, like seen below.

  ngOnInit() {
    this.data.getVehicles().subscribe(data => console.log(data));
    this.data.getUsers().subscribe(data => console.log(data));
    this.data.getHackers().subscribe(data => console.log(data));
    this.data.getArticles().subscribe(data => console.log(data));
  }

But how to act now, if certain areas of UI require all the API’s response together?

That is where the “forkJoin” operators comes into play : forkJoin executes all Observables parallely and completes the execution only if all Observables emit the result.

Even in an unlikely scenario where one of the API is delayed, the forkJoin waits for it to complete.

Our code becomes like this.

   const observable = forkJoin({
      vehicles: this.data.getVehicles(),
      users: this.data.getUsers(),
      hackers: this.data.getHackers(),
      articles: this.data.getArticles(),
    });
    observable.subscribe({
      next: (value) => console.log(value),
      complete: () => console.log('Completes with Success!'),
    });


// output
// articles: Array[26]
// hackers: Array[30]
// users: Array[10]
// vehicles: Array[25]
// Completes with Success!

The final response object will have properties that are defined in forkJoin such as vehiclesusershackers and articles.

If any one HTTP call fails, the entire forkJoin mechanism fails and throws an error.

combineLatest

combineLatest is similar to forkJoin, except that it combines the latest results of all the observables and emits the combined final value.

const observable = combineLatest({
      vechicles: this.data.getVehicles(),
      users: this.data.getUsers().pipe(delay(2000), startWith(null)), // Simulate network delay
      hackers: this.data.getHackers(),
      articles: this.data.getArticles().pipe(delay(500), startWith(null)),  // Simulate network delay
    });
    observable.subscribe({
      next: (value) => console.log(value),
      complete: () => console.log('Completes with Success!'),
    });


// Output
// {vechicles: Array[25], users: null, hackers: Array[30], articles: null}

// After 500 milliseconds
// {vechicles: Array[25], users: null, hackers: Array[30], articles: Array[26]…}

// After 2000 milliseconds
// {vechicles: Array[25], users: Array[10], hackers: Array[30], articles: Array[26]}

For the sake of network delay, we introduced delay and startsWith. So initially the users and articles property starts with null and as soon as the data is retrieved. Both the properties are populated with latest responses.

And all responses are combined.

In conclusion, both forkJoin and combineLatest produce similar results but forkJoin emits the response only after all the Observables completes. Whereas with combineLatest, we can trigger some Observable with “startWith” value, and let the operator emitting responses as soon as other Observable starts completing.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *