RxJS: Avoiding takeUntil Leaks

Nicholas Jamieson
3 min readMay 27, 2018
Photo by Tim Gouw on Unsplash

Using the takeUntil operator to automatically unsubscribe from an observable is a mechanism that’s explained in Ben Lesh’s Don’t Unsubscribe article.

It’s also the basis of a generally-accepted pattern for unsubscribing upon an Angular component’s destruction.

For the mechanism to be effective, operators have to be applied in a specific sequence. And, recently, I’ve seen code that used the takeUntil operator, but applied operators in a sequence that effected subscription leaks.

Let’s look at the problem sequence and at the reason for the leaks.

What’s the problem sequence?

If the takeUntil operator is placed before an operator that involves a subscription to another observable source, the subscription to that source might not be unsubscribed when takeUntil receives its notification.

For example, this use of combineLatest will leak the subscription to b:

And this use of switchMap will also leak the subscription to b:

Why does it leak?

The reason for the leak is more apparent when the deprecated combineLatest operator is replaced with the static combineLatest factory function, like this:

When the notifier emits, the observable returned by the takeUntil operator completes, automatically unsubscribing any subscribers.

However, the subscriber to c is not subscribed to the observable returned by takeUntil —…

Nicholas Jamieson

RxJS core team member; front-end developer; mentor; speaker; open-source contributor