0
0
Angularframework~5 mins

Unsubscribing and memory leaks in Angular

Choose your learning style9 modes available
Introduction

Unsubscribing stops your app from listening to things it no longer needs. This helps keep your app fast and avoids memory leaks, which slow it down over time.

When you subscribe to data streams like Observables in Angular components.
When you want to clean up resources before a component is removed from the screen.
When you use timers or event listeners that keep running after the component is gone.
When you want to prevent your app from using too much memory and crashing.
When you notice your app getting slower after using it for a while.
Syntax
Angular
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-example',
  template: `<p>Example works!</p>`
})
export class ExampleComponent implements OnDestroy {
  private subscription: Subscription;

  constructor() {
    this.subscription = someObservable.subscribe(data => {
      // handle data
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Always unsubscribe in the ngOnDestroy lifecycle method to avoid memory leaks.

You can store multiple subscriptions in a Subscription object and unsubscribe all at once.

Examples
Basic example of subscribing and unsubscribing from an Observable.
Angular
this.subscription = observable.subscribe(value => {
  console.log(value);
});

ngOnDestroy() {
  this.subscription.unsubscribe();
}
Manage multiple subscriptions together and unsubscribe all at once.
Angular
private subscriptions = new Subscription();

this.subscriptions.add(observable1.subscribe());
this.subscriptions.add(observable2.subscribe());

ngOnDestroy() {
  this.subscriptions.unsubscribe();
}
Use takeUntil with a Subject to automatically unsubscribe when the component is destroyed.
Angular
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';

private destroy$ = new Subject<void>();

observable.pipe(takeUntil(this.destroy$)).subscribe();

ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}
Sample Program

This component counts seconds using an Observable timer. It unsubscribes when the component is removed to stop counting and free memory.

Angular
import { Component, OnDestroy } from '@angular/core';
import { interval, Subscription } from 'rxjs';

@Component({
  selector: 'app-timer',
  template: `<p>Seconds passed: {{seconds}}</p>`
})
export class TimerComponent implements OnDestroy {
  seconds = 0;
  private timerSubscription: Subscription;

  constructor() {
    const timer$ = interval(1000); // emits every second
    this.timerSubscription = timer$.subscribe(() => {
      this.seconds++;
    });
  }

  ngOnDestroy() {
    this.timerSubscription.unsubscribe();
  }
}
OutputSuccess
Important Notes

Not unsubscribing can cause your app to slow down or crash because it keeps running code you don't need.

Angular's async pipe automatically unsubscribes for you in templates.

Use tools like browser DevTools to check for memory leaks by watching memory usage over time.

Summary

Always unsubscribe from Observables to avoid memory leaks.

Use ngOnDestroy to clean up subscriptions when components are removed.

Use helpers like Subscription or takeUntil to manage multiple subscriptions easily.