javascript / intermediate
Snippet
Optimizing Search with RxJS switchMap
Using switchMap for search ensures that if a new search term is entered before the previous request finishes, the old request is cancelled, preventing race conditions.
snippet.js
1
2
3
4
5
6
7
8
9
10
import { FormControl } from '@angular/forms';import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs';searchControl = new FormControl('');results$ = this.searchControl.valueChanges.pipe(debounceTime(300),distinctUntilChanged(),switchMap(term => this.apiService.search(term)));
angular
Breakdown
1
debounceTime(300)
Wait 300ms after the last keystroke before triggering the search.
2
distinctUntilChanged()
Only trigger if the search term is different from the last one.
3
switchMap(...)
Cancels the previous internal subscription (API call) when a new value arrives.