javascript / intermediate
Snippet
Preventing Race Conditions with switchMap
In Angular search implementations, switchMap is crucial. It cancels the previous observable when a new value arrives. This prevents 'race conditions' where an older, slower network request might overwrite a newer one.
snippet.js
1
2
3
4
5
this.searchTerms$.pipe(debounceTime(300),distinctUntilChanged(),switchMap(term => this.http.get(`/api/search?q=${term}`))).subscribe(results => this.results = results);
angular
Breakdown
1
debounceTime(300)
Waits for 300ms of silence before emitting the last value.
2
distinctUntilChanged()
Only emits if the current value is different from the last.
3
switchMap(...)
Switches to a new inner Observable and cancels the previous one.