Angular2: Unsubscribe from http observable in Service
A Service in Angular is a singleton. This means that the service will exist for the entire lifespan of your application.
The reason that you need to unsubscribe from an observable, is to avoid memory leaks. When do you get memory leaks? If something has been garbage collected while it was still subscribed to an observable, event listener, socket, ...
Since an Angular service never get's destroyed, unless your entire application get's destroyed, there is no real reason to unsubscribe from it. The observable will either complete or error or keep going as long as your application does.
Conclusion: Unsubscribing in a service is kind of pointless, since there is no chance of memory leaks.
I disagree with KwintenP answer. Yes in case of observable to HttpClient call there is no need to unsubscribe as Vladimir mentioned correctly however in other observables you may definitely need to unsubscribe in a service.
Let see simple example: Assume we have a store that send observables and in the store we have a clicker
observable that fire true
whenever there is a click on the right mouse (for some weird reason)
And assume we have MyWeirdService
that do the following:
class MyWeirdService {
doSomethingUnthinkableManyTimes() {
this.store.select('clicker').subscribe(() => {
console.log("Hey what do you know, I'm leaking");
});
}
}
this.store.select('clicker')
returns an observable that we registering a new handler to it on every call to doSomethingUnthinkableManyTimes
without cleaning it resulting in memory leak that will stay as long as the service is there (application lifetime in many cases)
Bottom line you don't need to unsubscribe in the case above of Http as Vladimir explained it well but in other cases you may need it.
-------------- Edition ------------
To solve that issue in my example, just add take(1)
and it will unsubscribe automatically after each stream is fired:
class MyWeirdService {
doSomethingUnthinkableManyTimes() {
this.store.select('clicker')
.pipe(take(1))
.subscribe(() => {
console.log("What a relief, I'm not leaking anymore");
});
}
}
You don't need to unsubscribe from observable created by Http
or HttpClient
because it is finite observable (value will be emitted only once and complete
will be called).
However, you CAN unsubscribe from the observable created by HttpClient
to cancel the request. It mean you are no longer interested in data returned by the request.