Search code examples
typescriptrxjsobservablerxjs6

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 ?


Solution

  • 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();
      }
    }