Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of using SubSink instead of a Subscriptions array

I just watched a ngConf video of John Papa talking about SubSink as a best practice in order to unsubscribe from obversables.

I was actually using Subscriptions[] then push subscriptions into it then forEach unsubscribe at cmp destroy.

Is their something I missed or is it just a readability improvment to use SubSink ?

like image 799
The Segfault Avatar asked May 20 '19 07:05

The Segfault


2 Answers

Another way, without installing third party libraries is to group subscriptions up with .add() method

export class CustomerComponent implements OnInit, OnDestroy {
  constructor(
    private dataService: DataService
  ){}

  private subs = new Subscription();

  ngOnInit() {
    this.subs.add(this.dataService.getCustomer().subscribe());
    this.subs.add(this.dataService.getProducts().subscribe());
  }

  ngOnDestroy() {
    this.subs.unsubscribe();
  }
}
like image 189
Shogg Avatar answered Oct 06 '22 18:10

Shogg


Adopting this way has at least one benefit - you move this code outside of your application logic. Because unsubscribing is just a clean up (a must). It is not related with the logic you create in your app.

And moving one step further, you can omit ngOnDestroy from components and create one adapter with NgOnDestroy implemented and place all logic there.

import { OnDestroy } from '@angular/core';
import { SubSink } from './sub-sink';

/**
* A class that automatically unsubscribes all observables when 
* the object gets destroyed
*/
export class UnsubscribeOnDestroyAdapter implements OnDestroy {

/**The subscription sink object that stores all subscriptions */
subs = new SubSink();

/**
* The lifecycle hook that unsubscribes all subscriptions 
* when the component / object gets destroyed
*/
ngOnDestroy(): void {
   this.subs.unsubscribe();
}

How to automatically unsubscribe your RxJs observables

Other than that, it is a very tiny package, only few lines of code. Thanks for sharing :)

like image 42
Julius Dzidzevičius Avatar answered Oct 06 '22 17:10

Julius Dzidzevičius