0Pricing
Angular Academy · Lesson

Unsubscribing and Memory Leaks

Avoid leaks with takeUntilDestroyed.

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(); }
}

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