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
1×
Become a member
to unlock all features

Level Up!

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

Autoplay

    Implement RxJS `switchMap` by Canceling Inner Subscriptions as Values are Passed Through

    John LindquistJohn Lindquist
    rxjsRxJS
    ^6.0.0

    switchMap is mergeMap that checks for an "inner" subscription. If the "inner" subscription exists, switchMap unsubscribes from that "inner" subscription which effectively "cancels" any pending pushes.

    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
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: While merge map allows every value to go through, you can see that 1, 2, 3, 4 is 1, 2, 3, 4. If I were to use switch map instead, so if we import switch map. Let's save. I'll click 1, 2, 3, 4, 5, and you can see that it cancels the first four and only does number 5. I'll do 6, 7, 8, 9, 10, you'll only see 10 come out.

    There is that idea of canceling observables that haven't pushed values through yet to our subscriber. Implementing my switch map will look very similar to my merge map, so that my switch map and rename my merge subscriber to my switch map subscriber.

    Right now, we have the original behavior where those are being merged rather than switched. All I need to do here is create a field. I'm just going to call this inner subscription. This inner subscription is going to point to this oberservable.subscribe.

    Say, this.innersubscription, which will allow me to unsubscribe from this observable. All I really need to do is say, if this.innersubscription, and make sure I spell that correctly, subscription. If that does exist, I'll just say this.innersubscription.unsubscribe.

    I'll hit save. Now, when I click 1, 2, 3, 4, 5, all I get from the inner is 5, because each click unsubscribed from the previous one that was held. 6, 7, 8, 9, 10, and again all we get out from the inner is 10, because again each click unsubscribed from that previous observable.

    Really the difference between merge map and switch map is, if I comment this out, I have my merge map behavior. If I put it back in, I now have my switch map behavior.