I know that it's good practice to unsubscribe from Observable to prevent memory leak.
But if it's Cold Observable should I also unsubscribe from it?
For example one that is returned by Http.get()
You don't need to do it. The HTTP observable is calling complete immediately after the action is done.
From the source code sources I can see that unsubscribe
is called on error and on complete.
protected _error(err: any): void {
this.destination.error(err);
this.unsubscribe();
}
protected _complete(): void {
this.destination.complete();
this.unsubscribe();
}
I went further and did a small experiment by adding unsubscribe
with a timeout
var subscription = this.http.get(`apiurl`)
.subscribe(response => {
setTimeout(function(){
debugger;
subscription.unsubscribe(); }, 30);
});
If I step inside of unsubscribe
to
Subscriber.prototype.unsubscribe = function () {
if (this.closed) { // this.closed is true
return;
}
this.isStopped = true;
_super.prototype.unsubscribe.call(this);
};
then this.closed == true
, which means unsubscribe
was called before.
So yes, now I can say for sure you don't need to unsubscribe :)