Blog>
Snippets

Unsubscribe from Observables

Unsubscribe from observables in the ngOnDestroy lifecycle hook to avoid memory leaks and unintended execution of observables.
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-sample-component',
  template: '<p>Sample Component</p>'
})
export class SampleComponent implements OnDestroy {
  private subscription: Subscription;

  constructor() {
    // Suppose we have an observable that we subscribe to
    const observable = this.getObservable();
    this.subscription = observable.subscribe(data => {
      // handle the data from the observable
      console.log(data);
    });
  }

  getObservable() {
    // Example: creating the Observable (here using RxJS)
    return new Observable(subscriber => {
      // Pushing data to subscribers
      subscriber.next('data emitted');
    });
  }

  // Called once, just before the instance of SampleComponent is destroyed
  ngOnDestroy() {
    // Unsubscribe to ensure no memory leaks
    this.subscription.unsubscribe();
  }
}
This example shows how to use the ngOnDestroy lifecycle hook in an Angular component to unsubscribe from an observable to avoid memory leaks. It creates an instance of a subscription to an observable in the constructor, which is then unsubscribed in the ngOnDestroy method.