In a previous post we have seen how the forkJoin operator is used to group multiple http requests (basically group observables) and take action only when all the requests have returned, i.e, we are waiting until all the http calls are finished.
But, what if we do not want to wait until all are done?, we only need to wait until atleast one http request has completed, in other words, emit value every time any of the source Observables emit after they’ve emitted at least once.
This scenario makes sense when we know certain http requests might take longer time than others, but still take actions based on other returned responses. For this use-case we use combineLatest.
Let’s look at an example to illustrate how combineLatest can be used in this scenario.
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { combineLatest } from 'rxjs';
@Component({
selector: 'app-example',
template: `
<div>
<p>Data 1: {{ data1 }}</p>
<p>Data 2: {{ data2 }}</p>
<p>Data 3: {{ data3 }}</p>
</div>
`
})
export class ExampleComponent implements OnInit {
data1: any;
data2: any;
data3: any;
constructor(private http: HttpClient) {}
ngOnInit() {
const request1 = this.http.get('https://api.example.com/data1');
const request2 = this.http.get('https://api.example.com/data2');
const request3 = this.http.get('https://api.example.com/data3');
// Using combineLatest to emit when any request returns a value after all have emitted at least once
combineLatest([request1, request2, request3]).subscribe(
([res1, res2, res3]) => {
// Update the component with new data whenever any observable emits after initial emission
this.data1 = res1;
this.data2 = res2;
this.data3 = res3;
// You can also implement logic to handle responses individually here
console.log('Responses received:', res1, res2, res3);
}
);
}
}
Key points:
combineLatestemits a new value whenever any of the source observables emit after all previous observables have emitted at least once.- This makes it suitable for scenarios where you want to react to each individual HTTP response as it arrives, without waiting for all to complete.
- Keep in mind,
combineLatestrequires all source observables to emit at least once before starting to emit combined values.
When to use combineLatest?
- When responses are independent and you want to process each as they arrive.
- When the order of responses doesn’t strictly matter.
- When some requests might take longer, but you want to update the UI or perform actions based on any response as soon as it arrives.
Summary
In situations where you need real-time updates or partial data from multiple HTTP requests, combineLatest is a powerful operator. Unlike forkJoin, which waits for all observables to complete, combineLatest provides a continuous stream of combined data, making your application more responsive.