⚠️ This lesson is retired and might contain outdated information.

Deal with out of order responses in Angular 2 using switchMap

Share this video with your friends

Social Share Links

Send Tweet

In this video you'll learn how to deal with out of order responses using the powerful switchMap operator

[00:00] Let's talk about out of order responses. Every time that we rest our fingers for a brief moment, a new request goes out. It may be totally possible that we have multiple requests in flight, waiting to get back to us with a response.

[00:13] Here's the thing. No one can guarantee that they'll come back in order. There may be load balances involved, that route requests to different servers, and they may handle requests at a different performance.

[00:25] What we see here is that the response for the character sequence an is coming back so late that it overrides the response list for ang which lives our UI in a state where the response list does not match the search field.

[00:39] Notice that we just simulate the shown behavior by adjusting our Wikipedia search service, so that it adds delay to search queries of two letter words. This is just to have a reliable source of out of order responses. It could totally happen in reality. With an X it's just one tiny operator changed to overcome this.

[00:56] Instead of using flatMap or matchMap, we'll use switchMap. Now think of switchMap as the equivalent of flatMap, but with a tiny twist. Every time we project the value into an observable, we subscribe to that observer, just as flatMap would do. We also automatically unsubscribe from the previous observable that we mapped to before.

[01:15] Let's change our import, and just change the usage of flatMap to switchMap. Now every time a new request goes out, we unsubscribe from the previous one. Let's turn to our browser and see that in action. We type an, rest a little, and then type the g. We know the an comes back one second later, but our app doesn't care about it anymore.