What is the best practice to unsubscribe within a Angular2 service from a http subscription?
Currently I do this but I\'m not sure if this will be the best way.
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");
});
}
}