Subscription management and takeUntilDestroyed
Why a manual .subscribe() call is a liability the moment you forget to clean it up, and the tools that remove the need to remember.
Subscription management and takeUntilDestroyed
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A manual `.subscribe()` call keeps running after a component is destroyed unless you explicitly unsubscribe — that's a live memory leak, not a theoretical one, the moment a user navigates away and back repeatedly.
- `takeUntilDestroyed()` ties a subscription's lifetime directly to the component's own, so it completes automatically on destroy with no `ngOnDestroy` boilerplate required.
- The async pipe remains the preferred default over any manual subscription — it never creates a subscription-cleanup problem in the first place, because there's no manual subscription to forget.
A subscription doesn’t know when your component dies
.subscribe() starts an observable running and keeps it running until one of
two things happens: the observable completes on its own, or something explicitly
unsubscribes. Neither of those is automatically tied to a component’s own
lifecycle. Subscribe to a long-lived stream — a BehaviorSubject from a shared
service, a setInterval-backed timer observable, a WebSocket feed — inside a
component, and that subscription has no idea the component was destroyed. It
keeps running, holding a reference to callback code that touches an instance
that no longer exists on screen. Do this inside a component a user navigates to
and away from repeatedly, and you accumulate one orphaned subscription per visit
— a textbook memory leak, and one that’s easy to miss in development because a
single test run rarely does enough navigate-away-and-back cycles to notice.
The old discipline: manual unsubscribe in ngOnDestroy
private sub = this.userService.currentUser$.subscribe((user) => (this.user = user));
ngOnDestroy() {
this.sub.unsubscribe();
}
This works, and for a long time it was simply the discipline every manual
subscription required: store the Subscription object, call .unsubscribe()
in ngOnDestroy. It’s exactly the cleanup job ngOnDestroy was introduced for,
several lessons back — but it has an obvious failure mode: it only works if you
remember to do it, every single time, for every manual subscription, and nothing
enforces that you did. A component with five manual subscriptions needs five
correctly-wired cleanups, or a combined Subscription object collecting all
five — more bookkeeping, more chances to miss one.
takeUntilDestroyed(): tying the subscription to the component automatically
this.userService.currentUser$
.pipe(takeUntilDestroyed())
.subscribe((user) => (this.user = user));
takeUntilDestroyed() is an operator that automatically completes the stream
it’s piped into once the current component is destroyed — it reads the
component’s DestroyRef (Angular’s own handle on “this thing is about to be torn
down”) and wires the subscription’s lifetime to it directly, with no manual
ngOnDestroy override required. One line in the pipe chain replaces the
store-a-Subscription-and-unsubscribe-in-ngOnDestroy pattern entirely, and —
unlike that pattern — there’s nothing left to forget, because the cleanup is
attached at the point the subscription is created, not somewhere else you have
to remember to also write.
Why the async pipe is still the better default where it fits
Everything above is about managing a subscription correctly. The async pipe,
covered a few lessons back, sidesteps the entire problem: it subscribes and
unsubscribes on its own, with no Subscription object for your code to ever
hold or forget. takeUntilDestroyed() matters specifically for the cases the
async pipe can’t cover — subscribing inside a method rather than a template, or
needing to run side-effect logic in the subscription callback rather than just
displaying a value. Where the async pipe fits the job, it remains the simpler
default; takeUntilDestroyed() is the right tool for the manual subscriptions
that are genuinely unavoidable.
This lesson’s video covers takeUntilDestroyed() directly from an Angular GDE’s
perspective; the linked “deeper” video makes the broader case for why manual
.subscribe() calls are riskier than they look, with a live demonstration of
the leak this lesson describes.
Check yourself
A component calls `this.userService.currentUser$.subscribe(user => this.user = user)` inside ngOnInit, with no corresponding cleanup. What actually happens to that subscription when the component is destroyed and recreated five times (e.g. by navigating away and back)?
Each mount creates a new subscription that's never torn down, so after five mount/destroy cycles you have five separate, still-active subscriptions all still running — each one holding a reference to the destroyed component instance, which is exactly the shape of a memory leak and, depending on what the subscription does, potentially duplicated side effects too.
What does `takeUntilDestroyed()` need in order to know when to complete a subscription, and where can it be called from?
It needs an injection context — by default it reads the current component's `DestroyRef` automatically when called during construction (e.g. as a field initializer), so the subscription completes exactly when that component is destroyed. Called outside an injection context, it needs an explicit `DestroyRef` passed in instead.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.