Angular & switchMap

Sk Asik
2 min readJul 2, 2020

--

Using the RXJS switchMap operator

Photo by Caspar Camille Rubin on Unsplash

Consider a situation where we need to quickly change filters or select an option.
To fetch a particular option, it will take the server a few extra seconds to reply than while fetching others. After we paused for a bit, we decide to select another option. The server replies quickly with the latest option, but few seconds later we get the response of the previous selection due to its higher response time. This will confuse the user.
Enter switchMap.

To resolve this, switchMap enables us to automatically unsubscribe from any previous observable when a new event is created.

using switchmap
switchmap implementation

We have an EventEmitter (change) is fired when a button is clicked. While we perform the service api call, if another button is clicked, we unsubscribe from that event and that api call is cancelled.

switchmap in action

Thanks for reading!

--

--

Sk Asik

I am Sk Asik and I’m a software developer. I am young into my career, constantly learning and hoping to share.