Always unsubscribe. No exceptions. Debate closed.
Daniel Glejzner
Posted on April 11, 2024
So many years with Angular.
So many years with RxJS.
Yet people still fight over "when NOT to unsubscribe".
Truth is. It's not even worth the conversation.
Just unsubscribe always. Simple.
I have recently posted the same advice on my social media(X/LinkedIn).
While majority agreed without a doubt. About 10% decided that it's a perfect opportunity to showcase deep and expert knowledge of how there is NO NEED to always unsubscribe.
The prime and crown example:
- HttpClient cold observable
I have been told that:
- It's a terrible advice
- It's a big overhead to always unsubscribe
- People should never follow this advice
- It's absolutely wrong
- It's redundant code
- It's a bold assumption
- Go ask Angular Team and so on...
Yes technically HttpClient completes automatically in like 99% of cases.
However this doesn't mean that you have to deliberately find and safe guard places where you subscribe to HttpClient Observable to avoid unsubscribing.
Simple "Why":
- It doesn't make any sense
- There is 0 overhead to unsubscribe since you have to do it in other places as well ( should be in your blood already cmon!"
- Value consistency over "being smart about things"
- Never think about when not to unsubscribe and focus on important things.
- Value consistency...
- Value consistency...
Not convinced? Advanced "Why":
- Citing a friend, because i could have not put it together in a batter way:
- Additionally this conversation has been "silently" resolved in one of the GitHub issues from 2022. Feedback from "Engineering" means response from devs.
source: https://github.com/angular/angular/issues/46542
- And finally in new Angular docs website. It's clearly stated that:
Once the response returns, Observables from HttpClient usually complete (although interceptors can influence this).
Because of the automatic completion, there is usually no risk of memory leaks if HttpClient subscriptions are not cleaned up. However, as with any async operation, we strongly recommend that you clean up subscriptions when the component using them is destroyed, as the subscription callback may otherwise run and encounter errors when it attempts to interact with the destroyed component.
source: https://angular.dev/guide/http/making-requests#http-observables
Now you can use this resource if your teammates keep nitpicking that you are unsubscribing from HttpClient Observables. Or any other they think it's "safe" not to do it.
Tip: Avoid subscribing in first place, do everything to end up with async pipe.
PS: as of Angular v16 - the best way to unsubscribe is by using takeUntilDestroyed()
Like my stuff? Follow me on LinkedIn or X
Big things happening at angularspace.com ( Early Access )
Posted on April 11, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.