RxJS & Reactive Programming
Angular Unsubscribe and Memory Leaks
A manual subscription keeps running after its component is destroyed unless it is unsubscribed, which leaks memory and can throw errors when the callback touches a destroyed view.
What is Unsubscribe and Memory Leaks in Angular?
A manual subscription keeps running after its component is destroyed unless it is unsubscribed, which leaks memory and can throw errors when the callback touches a destroyed view.
Unsubscribe and Memory Leaks example
TypeScript
// 1. best — no manual subscription at all
jobs$ = this.api.getJobs(); // consumed with | async
// 2. takeUntilDestroyed (Angular 16+)
constructor() {
this.api.getJobs()
.pipe(takeUntilDestroyed())
.subscribe(jobs => (this.jobs = jobs));
}
// 3. classic destroy subject
private destroy$ = new Subject<void>();
ngOnInit() {
this.api.getJobs().pipe(takeUntil(this.destroy$)).subscribe(/* … */);
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}Key points to remember
- HttpClient calls complete after one value, so they leak far less — but route params, valueChanges and interval never complete.
- takeUntilDestroyed must be called in an injection context, or given a DestroyRef.
- Prefer the async pipe; it removes the whole problem.
Common mistakes with Unsubscribe and Memory Leaks
- Assuming every Observable completes on its own.
- Calling destroy$.next() without complete(), leaving the Subject itself alive.
Angular Unsubscribe and Memory Leaks— Interview Questions & FAQs
Do I need to unsubscribe from HttpClient calls?+
Usually not — they emit once and complete. But subscriptions to route params, form valueChanges, intervals and Subjects never complete on their own and must be cleaned up.
