Unsubscribing and Memory Leaks
Avoid leaks with takeUntilDestroyed.
Unsubscribing and Memory Leaks is a free Angular Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Angular Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The memory leak problem
If you subscribe to a long-lived observable in a component and never unsubscribe, the callback keeps running after the component is destroyed. This leaks memory and can cause errors or duplicated work.
Manual unsubscribe
The basic fix: store the Subscription and unsubscribe in ngOnDestroy.
import { Component, OnDestroy } from '@angular/core';
import { Subscription, interval } from 'rxjs';
export class WidgetComponent implements OnDestroy {
private sub = interval(1000).subscribe(n => console.log(n));
ngOnDestroy() { this.sub.unsubscribe(); }
}Managing multiple subscriptions
A single Subscription can collect children with .add(), then one unsubscribe() tears them all down.
private subs = new Subscription();
ngOnInit() {
this.subs.add(a$.subscribe());
this.subs.add(b$.subscribe());
}
ngOnDestroy() { this.subs.unsubscribe(); }takeUntilDestroyed
Angular provides takeUntilDestroyed(), which auto-completes the stream when the component is destroyed — no manual ngOnDestroy needed.
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
export class WidgetComponent {
constructor() {
interval(1000)
.pipe(takeUntilDestroyed())
.subscribe(n => console.log(n));
}
}Injection context requirement
Called with no argument, takeUntilDestroyed() must run in an injection context (like the constructor). Outside it, pass a DestroyRef explicitly.
import { inject, DestroyRef } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
const destroyRef = inject(DestroyRef);
ngOnInit() {
source$.pipe(takeUntilDestroyed(destroyRef)).subscribe();
}The takeUntil pattern (classic)
Before takeUntilDestroyed, the standard pattern used a Subject that emits in ngOnDestroy.
private destroy$ = new Subject<void>();
ngOnInit() {
source$.pipe(takeUntil(this.destroy$)).subscribe();
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}Streams that complete need no cleanup
HttpClient requests emit once then complete, so they self-clean. You generally do not need to unsubscribe from a single HTTP call — though takeUntilDestroyed is still safe.
The async pipe handles it for you
The best approach for templates: let the async pipe subscribe and unsubscribe automatically. We cover it in the next lesson.
// template:
// <div>{{ user$ | async | json }}</div>
// No manual subscribe / unsubscribe neededSigns of a subscription leak
Duplicate network requests, handlers firing after navigation, growing memory in devtools, or "Cannot read property of destroyed view" errors often point to forgotten unsubscriptions.
toSignal also auto-cleans
Converting an observable to a signal with toSignal() also unsubscribes automatically when the owning context is destroyed.
import { toSignal } from '@angular/core/rxjs-interop';
user = toSignal(this.http.get('/api/me'));
// auto-unsubscribed on destroyChoosing an approach
Prefer async pipe or toSignal in templates; use takeUntilDestroyed() for manual subscriptions; fall back to a Subscription collection only when needed.
Quick Check
Test your understanding of unsubscribing.
Recap: Unsubscribing & Memory Leaks
Always tear down long-lived subscriptions.
takeUntilDestroyed()auto-completes on destroy.- The
asyncpipe andtoSignal()manage subscriptions for you. - Single HTTP calls self-complete.
Next: the async pipe in depth.
Frequently asked questions
Is the “Unsubscribing and Memory Leaks” lesson free?
Yes — the full text of “Unsubscribing and Memory Leaks” is free to read here on the web, and the Angular Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Angular Academy course, upgrade to CoddyKit PRO.
What will I learn in “Unsubscribing and Memory Leaks”?
Avoid leaks with takeUntilDestroyed. You practise Angular Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Angular Academy?
No prior experience is required. Angular Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Unsubscribing and Memory Leaks” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Angular Academy lesson?
Yes. Every Angular Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Observables and Subscriptions
- Subjects and BehaviorSubject
- Unsubscribing and Memory Leaks
- The async Pipe