Sub topic 4
Unsubscribing Safely and Avoiding Memory Leaks
This chapter assumes you know Angular components and lifecycle hooks such as ngOnInit and ngOnDestroy. It also assumes you know dependency injection with inject() and the observable, observer, and subscription model from the first chapter. You will learn when a subscription must be closed, the three main ways to close one, and the mistakes that leave streams running after a component is gone.
Why Subscriptions Leak
A subscription is a live link between a producer and an observer. It stays open until one of three things happens:
- The producer sends
complete. - The producer sends
error. - The consumer calls
unsubscribe().
Angular destroys components all the time: when you navigate, when an @if block turns false, or when a list item is removed. Destroying a component does not close the subscriptions it opened. If the stream never completes, the observer callback keeps a reference to the component instance. The garbage collector cannot free the component, and the callback keeps running against a component nobody can see.
The symptoms build up slowly. Memory grows on each navigation, console.log lines print twice and then three times, and duplicate HTTP requests fire from components that no longer exist.
Finite and Infinite Streams
Whether a leak is possible depends on whether the stream ends by itself.
| Source | Completes on its own? | Must you unsubscribe? |
|---|---|---|
| `of(1, 2, 3)`, `from([...])` | Yes, synchronously | No |
| `HttpClient.get()` | Yes, after one response | Not for memory, but unsubscribing cancels an in-flight request |
| `interval()`, `timer(0, n)` | No | Yes |
| `fromEvent(window, 'resize')` | No | Yes |
| `FormControl.valueChanges` | No | Yes, unless the control dies with the component |
| `ActivatedRoute.paramMap` | Angular completes it when the route is destroyed | Usually not, but closing it is cheap insurance |
| `BehaviorSubject` in a root service | No | Yes |
Unsubscribing from an observable that has already completed is harmless. If you are unsure, unsubscribe.
Lifecycle of a Component Subscription
When unsubscribe() runs, the teardown function the producer returned (the clearInterval in chapter one's hand-built observable) is executed. Every operator in the chain also tears down its own resources, such as timers and inner subscriptions.
Technique 1: Manual Unsubscribe in ngOnDestroy
The most explicit approach is to keep the Subscription and close it in ngOnDestroy. A single parent Subscription can collect children with add(), so one call closes them all.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription, fromEvent, interval, map } from 'rxjs';
@Component({
selector: 'app-clock',
standalone: true,
template: `<p>Seconds: {{ seconds }} | Width: {{ width }}</p>`,
})
export class ClockComponent implements OnInit, OnDestroy {
seconds = 0;
width = window.innerWidth;
private readonly subs = new Subscription();
ngOnInit(): void {
this.subs.add(
interval(1000).subscribe(n => (this.seconds = n))
);
this.subs.add(
fromEvent(window, 'resize')
.pipe(map(() => window.innerWidth))
.subscribe(w => (this.width = w))
);
}
ngOnDestroy(): void {
this.subs.unsubscribe();
}
}This approach works anywhere, but it depends on discipline. Each new subscribe call must remember to add, and a parent Subscription that has been closed cannot be reused. Anything added to it later is closed at once.
Technique 2: takeUntilDestroyed
takeUntilDestroyed from @angular/core/rxjs-interop is an operator that completes the stream when the surrounding component, directive, pipe, or service is destroyed. Internally it uses DestroyRef, an injectable handle whose onDestroy callbacks run when the owning injector or view is torn down.
Called without arguments, it calls inject(DestroyRef) for you. That only works inside an injection context, which means a constructor, a field initializer, or a factory.
import { Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
standalone: true,
template: `<p>Tick {{ tick }}</p>`,
})
export class TickerComponent {
tick = 0;
constructor() {
interval(1000)
.pipe(takeUntilDestroyed())
.subscribe(n => (this.tick = n));
}
}Code in ngOnInit, in an event handler, or after an await is no longer in an injection context. In those places, inject DestroyRef as a field and pass it in explicitly:
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { fromEvent, map } from 'rxjs';
@Component({
selector: 'app-window-width',
standalone: true,
template: `<p>Width: {{ width }}</p>`,
})
export class WindowWidthComponent implements OnInit {
width = window.innerWidth;
private readonly destroyRef = inject(DestroyRef);
ngOnInit(): void {
fromEvent(window, 'resize')
.pipe(
map(() => window.innerWidth),
takeUntilDestroyed(this.destroyRef)
)
.subscribe(w => (this.width = w));
}
}You can also register your own cleanup with this.destroyRef.onDestroy(() => ...). This is useful for closing things that are not observables, such as a WebSocket or a third-party chart instance.
Technique 3: Take Only What You Need
When you only want the first value, end the stream right after it arrives:
take(1)completes after one emission. If the source completes with no values,take(1)completes silently.first()completes after one emission and errors withEmptyErrorif the source completes empty.first(predicate)waits for the first value that matches.
These operators do not protect you if the component dies before the first value arrives. For a slow source, combine them with takeUntilDestroyed.
Gotcha: Operator Order with takeUntil
Before takeUntilDestroyed existed, the common pattern was a destroy$ Subject that emitted in ngOnDestroy, paired with takeUntil(destroy$). Both operators have the same ordering trap. They only complete what sits above them in the pipe. If a flattening operator such as switchMap comes after them, its inner subscription survives.
The script below runs in plain Node with RxJS installed. A Subject is used here only as a manual trigger, and later chapters cover Subjects in detail.
import { Subject, finalize, interval, of, switchMap, takeUntil } from 'rxjs';
const destroy$ = new Subject<void>();
// Wrong: takeUntil sits above switchMap, so the inner interval survives.
of('start')
.pipe(
takeUntil(destroy$),
switchMap(() => interval(500)),
finalize(() => console.log('wrong: torn down'))
)
.subscribe(n => console.log('wrong', n));
// Right: takeUntil is last, so it unsubscribes the whole chain.
of('start')
.pipe(
switchMap(() => interval(500)),
takeUntil(destroy$),
finalize(() => console.log('right: torn down'))
)
.subscribe(n => console.log('right', n));
setTimeout(() => {
destroy$.next();
destroy$.complete();
console.log('destroy$ fired');
}, 1600);
setTimeout(() => process.exit(0), 3500);After "destroy$ fired", the "right" chain logs "right: torn down" and goes quiet. The "wrong" chain keeps printing until the process exits. The rule is to put takeUntil or takeUntilDestroyed last, unless a later operator is itself guaranteed to complete. The rxjs-x/no-unsafe-takeuntil ESLint rule enforces this ordering for you.
finalize is also a handy debugging tool. It runs on complete, on error, or on unsubscribe, so it tells you whether teardown actually happened.
Edge Cases
- Root services. A
providedIn: 'root'service lives as long as the app does. Subscriptions it opens on itself are fine. The danger is a service subscribing on behalf of a component and passing it callbacks. - Subscribing inside subscribe. Inner subscriptions created in a
subscribecallback are not tied to the outer one. Unsubscribing the outer subscription leaves them running. Use a flattening operator instead; a later chapter covers these. - Errors end subscriptions. After an
error, the subscription is closed. A stream that you expect to live for the component's lifetime will silently stop unless errors are handled. Error handling has its own chapter. - Templates. The
asyncpipe, covered in the next chapter, subscribes and unsubscribes for you. When a value is only shown in a template, theasyncpipe is usually the cleanest choice.
Choosing a Technique
| Situation | Preferred technique |
|---|---|
| Value only rendered in the template | `async` pipe |
| Subscription in a component, directive, or service | `takeUntilDestroyed` |
| Subscription created outside an injection context | `takeUntilDestroyed(destroyRef)` |
| Need only the first value | `take(1)` or `first()`, plus `takeUntilDestroyed` if the source is slow |
| Must cancel at an arbitrary moment, not at destroy | Keep the `Subscription` and call `unsubscribe()` |
| Older codebase without rxjs-interop | `destroy$` Subject with `takeUntil` last |
Exercise
A component's ngOnInit contains this.route.paramMap.pipe(takeUntilDestroyed(), switchMap(p => interval(1000))).subscribe(...). Name the two problems with this code and how to fix them.
Show answer
First, takeUntilDestroyed() with no argument is called outside an injection context, so it throws NG0203. Inject DestroyRef as a field and pass it in. Second, the operator sits above switchMap, so the inner interval would keep running after destroy. Move takeUntilDestroyed(this.destroyRef) to the end of the pipe.
Exercise
You call this.subs.unsubscribe() in a method called reset(), then later call this.subs.add(interval(1000).subscribe(...)). Does the interval run? Why?
Show answer
No. A closed Subscription immediately unsubscribes anything added to it later, so the interval is torn down at once. Create a new Subscription after closing the old one, or keep each subscription in its own field.
Exercise
Is it a memory leak to subscribe to http.get('/api/users') in a component without unsubscribing? What can still go wrong?
Show answer
It is not a lasting memory leak, because HttpClient observables complete after one response and release the observer. If the user leaves before the response arrives, though, the request is not cancelled, and the callback still runs against the destroyed component. That can cause wasted work or side effects such as navigation or toasts. Adding takeUntilDestroyed cancels the request on destroy.