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?
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
And this use of
switchMap will also leak the subscription to
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:
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