Read this article at Devto WebsiteFew of below content does not render properly so instead of reading here, you can read this in Devto instead.

Better way to unsubscribe in Angular

rxjsangulartypescript

You might be wondering why do we need to unsubscribe every subscriptions. Well, you can get the answer from our friend here Netanel Basal. He have a nice .gif example so check it out.

As time goes on, we(developer) really tired of keep repeating the same process:

1. Importing ngOnDestroy,
2. Implement the interface
3. Create public function ngOnDestroy() { … }
4. Create a variables to keep list of subscriptions
5. … 
6. …
7. And repeat the whole process for other components.

This is tedious and a waste productivity. So, I'm going to share a 2 approach on how to unsubscribe subscription easily. But let's start with normal approach.


1. Using Inheritance

Create a BaseComponent so that, whoever extends this component are able to easily add subscription and easily unsubscribe on destroy.

gist https://gist.github.com/AzrizHaziq/837befe71d64d5e73ae540e981ded24a file=base-inheritence.ts

And this is how to implement in component class.

gist https://gist.github.com/AzrizHaziq/837befe71d64d5e73ae540e981ded24a file=child-inheritence.component.ts

One caveat tho, if the component extends BaseComponent and it also have implement ngOnDestroy() you would have to add super.ngOnDestroy();

gist https://gist.github.com/AzrizHaziq/837befe71d64d5e73ae540e981ded24a file=any-child.ts

2. Decorators

I think this approach kinda complicated a little bit as it mutate prototype. BTW i'm using mixin approach. Plus is not battle tested with this.

gist https://gist.github.com/AzrizHaziq/837befe71d64d5e73ae540e981ded24a file=base-decorator.ts

And here how to implement it

gist https://gist.github.com/AzrizHaziq/837befe71d64d5e73ae540e981ded24a file=child-decorator.component.ts

Thats all, feel free to play around here.

stackblitz better-way-to-unsubscribe-in-angular view=both

Update

  • Decorator approach with previous example it doesn't really work
  • Added once method to auto close the subscription. Can be really help full for something like click button, then trigger one http, and after that close it. (save your time to import take)
  • Added type to functions params and return
  • I'm still having difficulty with the return type in Decorator approach. Any typescripts master, please help me with this.