Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsubscribing from Observable in a non-Component/Directive class

I've read tons of posts on unsubscribing from Observables 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 Observables in a non-component/directive class e.g. in a service or basically any other class that contains subscriptions to Observables?

like image 316
Alexander Abakumov Avatar asked Oct 19 '25 14:10

Alexander Abakumov


1 Answers

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).

like image 140
martin Avatar answered Oct 21 '25 02:10

martin