DEV Community

Cover image for DRY Way to Manage Subscriptions in Angular Components

DRY Way to Manage Subscriptions in Angular Components

Marko Stanimirović on September 28, 2021

Cover photo by Tim Swaan on Unsplash. This article explains how to manage subscriptions in Angular components without repeating the same teardown ...
Collapse
 
nikosanif profile image
Nikos Anifantis

Great article! 👌
I have written a similar article that describes 5 ways to unsubscribe observables and I think you just proposed the 6th! 🚀

Collapse
 
madhust profile image
Madhu Sudhanan P • Edited

Good one Nikos !!

Collapse
 
nikosanif profile image
Nikos Anifantis

Many many thanks Madhu!

Collapse
 
markostanimirovic profile image
Marko Stanimirović

Thanks Nikos!

Collapse
 
2advancesolutions profile image
Batman • Edited

It’s a good idea to destroy observables using a helper class but not recommend to do this way as it causes each class or component to inherit the helper class to just destroy a subscription. If you expect a observer and want to kill it just Do pipe(take(1)) and if you expect a promise like user profile api request use.toPromise() instead of .subscribe(). I say this from experience using to helper method just cause extra code that’s not need. But great Article

Collapse
 
ashmcconnell profile image
Ash McConnell

I quite like npmjs.com/package/@ngneat/until-de... . I think it's worth a look. I agree though that ComponentStore is fantastic :)

Collapse
 
ashmcconnell profile image
Ash McConnell

Sorry I skimmed and missed the subtleties of your approach, that's really nice :)

Collapse
 
markostanimirovic profile image
Marko Stanimirović

Thank you :)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
slavafomin profile image
Slava Fomin II

Wow, this is clever. This pattern will reduce a lot of boilerplate from my code, thanks!

Collapse
 
madhust profile image
Madhu Sudhanan P

Nice one !!

Collapse
 
ruslangonzalez profile image
Ruslan Gonzalez

Cool! How about the async pipe approach also?

Collapse
 
markostanimirovic profile image
Marko Stanimirović

Yes, async is always a great choice for displaying Observable results on a template :)

Collapse
 
markostanimirovic profile image
Marko Stanimirović

Thanks Ankita! I will :)