How would you combine two or more observables together, such as combining a user's search term and a selected filter category?
Short answer
The combineLatest operator lets you combine the most recent values from several observables into a single observable, emitting a new combined value whenever any one of the source observables emits, letting you react to changes across multiple independent streams together.
Advertisement
AModel answer
The combineLatest operator lets you combine the most recent values from several observables into a single observable, emitting a new combined value whenever any one of the source observables emits, letting you react to changes across multiple independent streams together.
combineLatest([searchTerm$, selectedCategory$]).pipe(
switchMap(([term, category]) => this.productService.search(term, category))
).subscribe((results) => this.results = results);Real-world example
A product search page automatically re runs its search whenever either the typed search term or the selected category filter changes, using combineLatest to react to both independent inputs together as a single combined stream.
Likely follow-ups
- How does combineLatest differ from the forkJoin operator, given both combine multiple observables?
- What happens if one of the combined observables never emits a value at all?
Related topics