⚠️ 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
Published 8 years ago
Updated 2 months ago

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.

egghead
egghead
~ 2 hours ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today