我知道取消订阅 Observable以防止内存泄漏是一种很好的做法.
但如果它是Cold Observable,我还应该取消订阅吗?
例如,返回的一个 Http.get()
你不需要这样做。HTTP 可观察对象在操作完成后立即调用完成。
从源代码来源我可以看到它unsubscribe在错误和完成时被调用。
protected _error(err: any): void {
this.destination.error(err);
this.unsubscribe();
}
protected _complete(): void {
this.destination.complete();
this.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
我进一步做了一个小实验,添加unsubscribe了超时
var subscription = this.http.get(`apiurl`)
.subscribe(response => {
setTimeout(function(){
debugger;
subscription.unsubscribe(); }, 30);
});
Run Code Online (Sandbox Code Playgroud)
如果我走进unsubscribe去
Subscriber.prototype.unsubscribe = function () {
if (this.closed) { // this.closed is true
return;
}
this.isStopped = true;
_super.prototype.unsubscribe.call(this);
};
Run Code Online (Sandbox Code Playgroud)
then this.closed == true,这意味着unsubscribe之前被调用过。
所以是的,现在我可以肯定地说您不需要取消订阅:)
小智 6
由于冷可观察量是有限的,您不必取消订阅。
对于 ReplaySubject,如果未提供缓存生命周期,您应该取消订阅
对于 AsyncSubject,如果未完成,您应该取消订阅
如果我错了或遗漏了什么,请告诉我。谢谢 ;)
| 归档时间: |
|
| 查看次数: |
579 次 |
| 最近记录: |