Using the RXJS switchMap operator
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.
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.
Thanks for reading!