What do the map, filter, and switchMap RxJS operators do, and when would you use each?
Short answer
map transforms each emitted value into something else, similar to the array method of the same name. filter only lets through values matching a specific condition.
Advertisement
AModel answer
map transforms each emitted value into something else, similar to the array method of the same name. filter only lets through values matching a specific condition. switchMap is used when an emitted value itself needs to trigger a new observable, such as a new HTTP request, automatically cancelling any previous still in progress request if a new value arrives first.
searchTerm$.pipe(
filter((term) => term.length > 2),
switchMap((term) => this.http.get(`/api/search?q=${term}`))
).subscribe((results) => this.results = results);Real-world example
A search box only sends a request once the user has typed at least three characters, and automatically cancels any still pending search request if the user keeps typing before it finishes, using filter and switchMap together.
Likely follow-ups
- Why does switchMap automatically cancel a previous still pending request, and why is that usually the desired behavior for search?
- How does switchMap differ from mergeMap and concatMap?
Related topics