RxJS Operator: switchMap
Deborah Kurata
Posted on August 19, 2021
The switchMap
RxJS Operator is a higher-order mapping operator that processes an emitted value but if another value is emitted, it will cancel that processing and switch over to the new value.
For example:
products$ = this.categorySelected$
.pipe(
switchMap(catId=>
this.http.get<Product[]>(`${this.url}?cat=${catId}`))
);
In the above code, the switchMap
will perform the HTTP get for the selected category. If a different category is selected, it will cancel that HTTP get request and perform an HTTP get for the newly selected category.
How Does switchMap Work?
We can think of the switchMap like a coach that can't decide which runner should run in a race. But ultimately, only their last choice will run.
Let's look at an Example
In this example, the user clicks the category with an id of 2, changes their mind and picks 3, then decides they really want category 1.
Following the numbers on the screen shot above:
- The switchMap issues a get request for category 2,
- then cancels that request and issues a get request for category 3,
- then cancels that request and issues a get request for category 1.
- Only the result for category 1 is emitted.
For this specific example, where the user can change their mind on the selected category, using switchMap is often the best choice. It will immediately react to the user's selection.
When Should We Use switchMap?
The switchMap operator is great for responding to user actions, such as this example of the user selecting a product category. It can then switch as the user changes their mind.
Also great for typeahead functionality.
Posted on August 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.