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
- Observables and Subscriptions
- Subjects and BehaviorSubject
- Unsubscribing and Memory Leaks
- The async Pipe