Skip to main content

How to avoid memory leaks in subscriptions?

To avoid memory leaks in subscriptions, the main rule is: unsubscribe in time.

Here's how it's done in practice:


1. Store the subscription and call unsubscribe()

ts
subscription: Subscription; ngOnInit() { this.subscription = this.myStream$.subscribe(data => ...); } ngOnDestroy() { this.subscription.unsubscribe(); // stream closed }

2. Use takeUntil() with a Subject

Good if you have many subscriptions:

ts
private destroy$ = new Subject<void>(); ngOnInit() { this.myStream$ .pipe(takeUntil(this.destroy$)) .subscribe(...); } ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); }

Everything inside takeUntil unsubscribes automatically.


3. Use the async pipe in the template

html
<div *ngIf="value$ | async as value">{{ value }}</div>

Angular itself unsubscribes when the component is destroyed. This is the safest option in a template.


4. take(n) and first() - for one-time subscriptions

If you only need one value from the stream:

ts
this.data$.pipe(first()).subscribe(...);

or

ts
this.data$.pipe(take(1)).subscribe(...);

The stream completes on its own, nothing to unsubscribe.


Conclusion:

To avoid leaks:

  • Always unsubscribe in ngOnDestroy()
  • Use takeUntil() or async
  • Don't leave infinite subscribe() calls without control

An unmanaged subscription = a hanging stream = a memory leak.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.