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

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 5 years ago

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.

Instructor: [00:00] 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.

[00:24] 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.

[00:47] 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.

[01:06] 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.

[01:33] 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.

[01:56] 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.

J. Matthew
J. Matthew
~ 5 years ago

Great explanation of switchMap!

My default Webpack build process breaks when I try to declare innerSubscription above the constructor. Seems like something is missing to handle that; not sure what or why. However, it's not necessary to declare the property. It is sufficient to reference and set this.innerSubscription inside _next. In fact, we're already doing that (working with an undeclared property) with this.fn.

Markdown supported.
Become a member to join the discussionEnroll Today