0
0
AngularHow-ToBeginner · 3 min read

How to Unsubscribe from Observable in Angular: Simple Guide

To unsubscribe from an Observable in Angular, store the subscription returned by subscribe() in a variable and call unsubscribe() on it when no longer needed. This is commonly done in the ngOnDestroy() lifecycle hook to clean up subscriptions and prevent memory leaks.
📐

Syntax

When you subscribe to an Observable, it returns a Subscription object. You use this object to stop receiving data by calling its unsubscribe() method.

  • const subscription = observable.subscribe(...); — subscribes and saves the subscription.
  • subscription.unsubscribe(); — stops the subscription.
typescript
const subscription = observable.subscribe(value => {
  console.log(value);
});

// Later when you want to stop listening
subscription.unsubscribe();
💻

Example

This example shows subscribing to a simple observable and unsubscribing in the Angular component's ngOnDestroy() method to avoid memory leaks.

typescript
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 subscription: Subscription;

  constructor() {
    const source = interval(1000); // emits every second
    this.subscription = source.subscribe(val => {
      this.seconds = val + 1;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe(); // clean up when component is destroyed
  }
}
Output
Seconds passed: 1 Seconds passed: 2 Seconds passed: 3 ... (increments every second until component is destroyed)
⚠️

Common Pitfalls

Common mistakes include:

  • Not unsubscribing at all, causing memory leaks.
  • Subscribing multiple times without unsubscribing previous subscriptions.
  • Trying to unsubscribe from an observable that does not return a subscription (like using async pipe instead).

Always store your subscription in a variable and unsubscribe properly.

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

@Component({
  selector: 'app-bad-example',
  template: `<p>Bad example</p>`
})
export class BadExampleComponent implements OnDestroy {
  private subscription: Subscription;

  constructor() {
    const source = interval(1000);
    // Wrong: subscribing multiple times without unsubscribing
    source.subscribe(val => console.log('First subscription:', val));
    source.subscribe(val => console.log('Second subscription:', val));

    // Correct way
    this.subscription = source.subscribe(val => console.log('Managed subscription:', val));
  }

  ngOnDestroy() {
    this.subscription.unsubscribe(); // Only unsubscribes managed subscription
  }
}
📊

Quick Reference

  • Subscribe: const sub = observable.subscribe(...);
  • Unsubscribe: sub.unsubscribe();
  • Best place to unsubscribe: ngOnDestroy() lifecycle hook
  • Use async pipe: Angular handles unsubscribe automatically in templates

Key Takeaways

Always save your subscription to a variable to unsubscribe later.
Call unsubscribe() in ngOnDestroy() to prevent memory leaks.
Avoid multiple subscriptions without unsubscribing previous ones.
Use Angular's async pipe in templates to auto-manage subscriptions when possible.
Unsubscribing stops the observable from sending more data and frees resources.