DEV Community

Cover image for Use subscription object to clear subscribes πŸ¦Έβ€β™‚οΈ
Alireza Razinejad
Alireza Razinejad

Posted on

Use subscription object to clear subscribes πŸ¦Έβ€β™‚οΈ

Cover image source

We all know we need to clear (unsubscribe) our subscriptions when ever component will be destroyed.

Let's see how we can use Subscription class from RxJs to do this. πŸ₯ƒ

Let's look at our component:

import {Component, OnInit} from "@angular/core";
import { Observable } from 'rxjs';

@Component({
  selector: 'app-componento',
  template: `<div>Component</div>`
})
export class Componento implements OnInit {
  obs: Observable<any> = new Observable;

  ngOnInit(): void {
    this.obs.subscribe(() => {});
  }
}
Enter fullscreen mode Exit fullscreen mode

Good, now let's how we can use subscription to unsubscribe on destroy

import {Component, OnDestroy, OnInit} from "@angular/core";
import { Observable, Subscription } from 'rxjs';

@Component({
  selector: 'app-componento',
  template: `<div>Component</div>`
})
export class Componento implements OnInit, OnDestroy {
  obs: Observable<any> = new Observable;
  subs: Subscription = new Subscription;

  ngOnInit(): void {
    this.subs.add(this.obs.subscribe(() => {}));
  }

  ngOnDestroy(): void {
    this.subs.unsubscribe();
  }
}
Enter fullscreen mode Exit fullscreen mode

That's it !

More readable version in case of having multiple observable, will be like this:

import {Component, OnDestroy, OnInit} from "@angular/core";
import { Observable, Subscription } from 'rxjs';

@Component({
  selector: 'app-componento',
  template: `<div>Component</div>`
})
export class Componento implements OnInit, OnDestroy {
  obs: Observable<any> = new Observable;
  obs2: Observable<any> = new Observable;
  obs3: Observable<any> = new Observable;
  subs: Subscription = new Subscription;

  ngOnInit(): void {
    this.subToOb();
    this.subToOb2();
    this.subToOb3();
  }

  ngOnDestroy(): void {
    this.subs.unsubscribe();
  }

  private subToOb(): void {
    this.subs.add(this.obs.subscribe(() => {}));
  }

  private subToOb2(): void {
    this.subs.add(this.obs2.subscribe(() => {}));
  }

  private subToOb3(): void {
    this.subs.add(this.obs3.subscribe(() => {}));
  }
}
Enter fullscreen mode Exit fullscreen mode

Have a good day 🍻

Top comments (0)