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

Already subscribed? Sign In

Autoplay

    Deal with out of order responses in Angular 2 using switchMap

    Christoph BurgdorfChristoph Burgdorf

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

    angularAngular
    ^2.0.0
    rxjsRxJS
    ^5.0.0
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    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.

    Discuss

    Discuss