I've read tons of posts on unsubscribing from Observable
s in Angular and all of them mention the need to do so in components/directives only.
So my question is:
Do we need to unsubscribe from Observable
s in a non-component/directive class e.g. in a service or basically any other class that contains subscriptions to Observable
s?
You unsubscribe in components because when you remove them from DOM (eg. with *ngIf
or whatever) RxJS chains would hold references to observers you created there. Thus introducing memory leaks.
In general you don't have to unsubscribe in services because they exist during the entire lifetime of your application.
However, in Angular you can create a component that for example provides a different service instance only to its descendants (this means you might have multiple instances of the same service class in your app). In such case you should unsubscribe manually (probably when destroying the component that defined them).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With