DEV Community

Amit Das
Amit Das

Posted on

Angular RxJS Unsubscriber

Unsubscriber

Unsubscriber for RxJS subscription to unsubscribe.

In Angular, we commonly used an RxJS subscription but sometimes we forget to unsubscribe it, which causes a memory leak. The advantages of using the Unsubscriber are that there is no need to manage the individual variables and unsubscribe to them (of course, it works fine, but it requires a little bit more code to write). Unsubscriber is a simple class to absorb RxJS subscriptions in an array.

Call unsubscribe() to unsubscribe all of them, as you would do
in your component library's unmount/onDestroy lifecycle event.

Installation

npm install unsubscriber --save
Enter fullscreen mode Exit fullscreen mode

Angular examples

There are 2 main ways to use the Unsubscriber: the "setter" way and the "add/array" way.

RxJS supports adding subscriptions to an array of subscriptions. You can then unsubscribe directly from that array. If you prefer this technique with Unsubscriber using the setter syntax below, then use that.

Technique Setter - Syntax

Example using the queue property to collect the subscriptions using a setter.

export class ExampleComponent implements OnDestroy {
  private bus = new Unsubscriber();

  ...
  this.bus.queue = observable$.subscribe(...);
  this.bus.queue = observable$.subscribe(...);
  this.bus.queue = observable$.subscribe(...);
  ...

  // Unsubscribe all subscription when the component dies/destroyed
  ngOnDestroy() {
    this.bus.unsubscribe();
  }
}
Enter fullscreen mode Exit fullscreen mode

Technique Array/Add - Syntax

Example using the .add technique. This is similar to what RxJS supports out of the box.

export class ExampleComponent implements OnDestroy {
  private bus = new Unsubscriber();

  ...

  this.bus.add(observable$.subscribe(...)); 

  this.bus.add(observable$.subscribe(...)); 

  // Add multiple subscriptions at the same time
  this.bus.add( 
    observable1$.subscribe(...),
    observable2$.subscribe(...),
    anotherObservable$.subscribe(...)
  ); 

  ...

  // Unsubscribe all subscription when the component dies/destroyed
  ngOnDestroy() {
    this.bus.unsubscribe();
  }
}
Enter fullscreen mode Exit fullscreen mode

Github Techindeck

Top comments (2)

Collapse
 
thavarajan profile image
Thavarajan

How it's different from sink

Collapse
 
spdocumentad profile image
Amit Das • Edited

Hi @thavarajan, thank s for your question. I have reviewed the sink, both are work on same methodology or way.