Angular Academy · Lesson

Unsubscribing and Memory Leaks

Avoid leaks with takeUntilDestroyed.

Lesson 3 of 413 steps

Unsubscribing and Memory Leaks is a free Angular Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Angular Academy learning path, and your progress syncs across the web and the CoddyKit app. The Angular Academy course includes 4 lessons in total.

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 needed

Signs 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 destroy

Choosing 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 async pipe and toSignal() manage subscriptions for you.
  • Single HTTP calls self-complete.

Next: the async pipe in depth.

Free to start

Learn HTML with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
38
Lessons
144

Frequently Asked Questions

Is the “Unsubscribing and Memory Leaks” lesson free?

Yes — any 3 lessons of the Angular Academy learning path, including “Unsubscribing and Memory Leaks”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Angular Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

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

  1. Observables and Subscriptions
  2. Subjects and BehaviorSubject
  3. Unsubscribing and Memory Leaks
  4. The async Pipe
← Back to Angular Academy