Tuesday, August 20, 2019

subscription spool

Here is a pattern which has emerged in the Angular 7 application I am working on. At a component we have a component-wide variable for holding all of the subscriptions to Observables that we will mess with on the TypeScript side like so:

public subscriptions = [];

 
 

We put stuff in like so:

ngOnInit() {
   this.subscriptions.push(
      this.store.select(getUserInfo).subscribe(user => {
         this.user = user;
         getNextSubscription(user);
      })
   );
}

 
 

We throw away everything like so:

ngOnDestroy() {
   this.subscriptions.forEach(item => {
      item.unsubscribe();
   });
}

 
 

The point of this is a management trick for managing more than one subscription. We just see one above, but there could be more, no?

No comments:

Post a Comment