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.


    Pause Until Another Stream Completes with exhaustMap in RxJS and Vue.js

    John LindquistJohn Lindquist
    5.5.12 - 6.4.0

    The switchMap operator is often referenced as the default operator when you need to switch to another stream (which happens when clicking a button switches to loading data). But in the scenario where you want the first stream (the button click) to "pause" until the second stream (the data loads) completes, exhaustMap is the proper operator to use.



    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




    Instructor: The concept of a disabled stream, and then disabling a button in the UI like this does prevent the user from mashing on this button by disabling the element. I can't mash on that until this is done loading.

    If I remove this disabled property, then I'll mash on this button with disabled removed. You watch the network panel. You'll see that a bunch of requests go out each time I click. While the UI was preventing it earlier, the stream itself was not preventing all of these requests.

    We can do that by changing our operator here from switchMap, which says that each time you try and push a value from here into switchMap, attempt to cancel what's going on in here and fire off a new one. Each time it clicked, it tried to fire off a new request.

    Where exhaustMap has the behavior of each time a value pushes from here into here, wait for this inner observable. Remember this loader observable that we created. Wait for this one to complete before firing off another one.

    I'll clear out our network. Make sure that we slow down our requests. Back in the network, if I mash on load, you can see only one request was made. Then another one was made and another.

    Each time, it's waiting for the previous one to complete, as you can see in the waterfall here. This step, then this step, then this step, then this step always waited for the previous one to complete.

    We'll contrast that with the waterfall of a switchMap. Now I'll mash on the button. You can see that each of those clicks made a request.

    The waterfall did not wait for the previous one to complete. It attempted to cancel and fire off a new one.

    Again, while our disabled stream works great for disabling in the UI -- so we'll leave it in there -- it's also good to understand that the proper operator in this scenario would be exhaustMap, so that it waits for the previous request to finish loading.