DEV Community

Cover image for Use subscription object to clear subscribes 🦸‍♂️
Alireza Razinejad
Alireza Razinejad

Posted on

2

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 🍻

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs