Sub topic 4
Unsubscribing Safely and Avoiding Memory Leaks
This chapter assumes you know how observables, observers, and subscriptions relate, and that you can write a standalone Angular component that uses dependency injection. It covers why subscriptions outlive components, the three main ways to end them, and the mistakes that cause leaks.
Why Subscriptions Leak
A subscription stays active until one of three things happens: the source completes, the source errors, or you call unsubscribe(). Angular destroys a component when you navigate away. It does not end the subscriptions that component created. If the source never completes, for example interval, a store's BehaviorSubject, or fromEvent on window, the observer keeps running. The observer's closure also holds a reference to the destroyed component, so the garbage collector cannot free it.
You see a leak as duplicated work. Visit a page five times and five copies of the same callback run on each tick.
Which Sources Need Cleanup
| Source | Completes on its own? | Needs cleanup? |
|---|---|---|
| `HttpClient` request | Yes, after one response | Usually no, but cleanup cancels a request that is still in flight |
| `of`, `from` an array | Yes, right away | No |
| `interval`, `fromEvent` | No | Yes |
| Router `paramMap`, form `valueChanges` | No (they end when their owner is destroyed) | Yes, as a habit |
| Service `BehaviorSubject` | No | Yes |
Option 1: Manual unsubscribe
Store the Subscription and end it in ngOnDestroy.
import { Component, OnDestroy } from '@angular/core';
import { interval, Subscription } from 'rxjs';
@Component({
selector: 'app-clock',
standalone: true,
template: `<p>{{ seconds }}</p>`,
})
export class ClockComponent implements OnDestroy {
seconds = 0;
private sub: Subscription = interval(1000).subscribe(n => (this.seconds = n));
ngOnDestroy(): void {
this.sub.unsubscribe();
}
}This works, but every new subscription needs its own field and its own cleanup line, so it is easy to forget one.
Option 2: takeUntilDestroyed
takeUntilDestroyed from @angular/core/rxjs-interop completes the stream when the component's DestroyRef fires. Call it with no argument inside an injection context, which means a field initializer or the constructor. Anywhere else, such as ngOnInit or an event handler, you must pass a DestroyRef.
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { fromEvent, interval, map } from 'rxjs';
@Component({
selector: 'app-tracker',
standalone: true,
template: `<p>{{ seconds }}s, width {{ width }}px</p>`,
})
export class TrackerComponent {
private destroyRef = inject(DestroyRef);
seconds = 0;
width = window.innerWidth;
constructor() {
interval(1000)
.pipe(takeUntilDestroyed())
.subscribe(n => (this.seconds = n));
}
startTracking(): void {
fromEvent(window, 'resize')
.pipe(
map(() => window.innerWidth),
takeUntilDestroyed(this.destroyRef)
)
.subscribe(w => (this.width = w));
}
}Option 3: Do not subscribe at all
The cleanest fix is to let Angular own the subscription. The async pipe, covered in the next chapter, subscribes from the template and unsubscribes on destroy. Use subscribe() in a component only when you need a side effect.
Common Mistakes
- Calling
takeUntilDestroyed()without arguments inngOnInit. It throws error NG0203 because there is no injection context. - Subscribing inside another
subscribecallback. The inner subscription is never cleaned up. Use a flattening operator instead. - Assuming
first()ortake(1)is always safe. If the source never emits, the subscription stays open.
Exercise
A component subscribes to this.cart.items$ (a BehaviorSubject-backed stream) inside ngOnInit using .pipe(takeUntilDestroyed()). The app throws NG0203. Give two ways to fix it.
Show answer
Move the subscription into the constructor or a field initializer, where an injection context exists. Or inject DestroyRef as a field and pass it, as in takeUntilDestroyed(this.destroyRef), which keeps the subscription in ngOnInit.
Exercise
Why does .pipe(takeUntilDestroyed(), switchMap(id => this.http.get(/api/items/${id}))) risk a leak, and how do you fix it?
Show answer
takeUntilDestroyed completes only the outer source. switchMap keeps its active inner subscription until that inner observable finishes, so a request that is still running can outlive the component. Move takeUntilDestroyed after switchMap so it ends the whole chain.