Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Deal with out of order responses in Angular 2 using switchMap


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



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.

    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.

    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.

    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.

    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.

    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.