0 day streak
javascript / intermediate
Snippet

Optimizing Search with switchMap

The switchMap operator is essential for search implementations. It cancels previous HTTP requests if a new search term is emitted before the previous request completed, preventing race conditions and saving bandwidth.

snippet.js
javascript
1
2
3
4
5
6
7
import { switchMap, debounceTime, distinctUntilChanged } from 'rxjs';
this.searchTerms.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(term => this.userService.search(term))
).subscribe(results => this.results = results);
angular
Breakdown
1
debounceTime(300)
Waits for 300ms of silence before emitting the last value.
2
switchMap(...)
Maps to a new observable and cancels the previous inner observable.