`add` Inner Subscriptions to Outer Subscribers to `unsubscribe` in RxJS

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 6 years ago

When subscribers create new "inner" sources and subscriptions, you run the risk of losing control of them when the outer subscriber unsubscribes. This is handled easily enough if you use the add method from the Subscriber class to add the "inner" subscription to the Subscriber.

Instructor: [00:00] A really important scenario we haven't covered is, what happens when this subscriber completes before this subscriber completes? This object is our subscriber, and you'll see the behavior right now, if I take until and all the save from event document key down which just means I'll type a key and this should stop.

[00:24] Save here, and I'll click 1, 2, 3, 4, 5, and then hit a key on my keyboard. You can see we got done, but stuff kept on happening. This done came from here, this subscriber, but my inner subscriber kept on pushing out nexts.

[00:41] If I were to use the real concat map and do the same thing, I'd go 1, 2, 3, 4, 5, hit a key, and you can see done and everything is stopped. Just to show that again, 1, 2, 3, 4, 5 and hit a key, done, nothing else happens.

[00:59] That's because, this complete is also telling this guy to complete and unsubscribe. Luckily for us, subscriber has a method called add which can simply take an inner subscription and say this add this.innersubscription.

[01:16] Let's save. Make sure I switch back to my concat map, my concat map.

[01:27] You can see if I go 1, 2, 3, 4, 5 and hit a key, that it is now done and nothing else is logged from that inner subscriber. This complete knows to stop and unsubscribe from this subscription.

[01:43] You can think of it like where we say subscribe here and pass in a subscriber using the operators will walk through using this call to source subscribe and pass in the other operators whereas the opposite would be this.add. Will let the parent subscriber know. We'll let this one to know that when unsubscribe is called, make sure and clear out those inner subscriptions.