Use of switchMap in Angular: Beginner’s guide

Sajin Kasim
3 min readDec 28, 2023

--

We often came across the requirement to make an API call to retrieve data corresponding to a change in an input field or button click. As we know the API calls take some time to retrieve the data and multiple clicks or multiple changes will invoke the API calls. There won’t be any specific order in which the response is received based on order of invocation. So the result might be wrong.

Let’s take an example of a form input to accept a date which validates the date from backend. So as soon as change occurs the API call will be invoked. If the response of invalid date comes last even though we entered valid date later, then UI will show an error. Thins is wrong. For this we need to change the mapping to the latest emitted change.

Let me explain this with an example of consoling sequence of number based on button click.

Here button click is initialized as an observable. On each button click, it will invoke the second observable which emit sequence of numbers on an interval of 1000ms

The problem here each time, when we make a click, new subscription will be made, and existing subscription will be there.

On click 1

On click 2

So on each click there’s new subscription is creating and the component will continue listening to previously subscribed observable. This makes performance issues as well was wrong output as the UI will be updated with wrong values.

Inorder to tackle this, RxJs library provides an operator named switchMap. What switchMap will do is that, it will cancel the existing subscription and map to latest emitted change. This helps to improve the performance as well as process the response correctly.

The above code can be changed like this.

Output on 3 clicks

Here, the switchMap operator cancels the existing subscription and map to latest change.

--

--

Sajin Kasim
Sajin Kasim

No responses yet