本文介绍了我应该取消订阅 Cold Observable 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道从 Observable 中取消订阅以防止内存泄漏是一种很好的做法.

I know that it's good practice to unsubscribe from Observable to prevent memory leak.

但是如果它是Cold Observable,我是否也应该取消订阅它?

But if it's Cold Observable should I also unsubscribe from it?

例如由 Http.get()

推荐答案

您不需要这样做.HTTP observable 在操作完成后立即调用完成.

You don't need to do it. The HTTP observable is calling complete immediately after the action is done.

来自源代码">来源unsubscribe 在错误和完成时被调用.

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();
}

我更进一步,通过添加带有超时的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);
            });

如果我进入unsubscribe

 Subscriber.prototype.unsubscribe = function () {
        if (this.closed) { // this.closed is true
            return;
        }
        this.isStopped = true;
        _super.prototype.unsubscribe.call(this);
    };

then this.closed == true,表示之前调用了unsubscribe.

then this.closed == true, which means unsubscribe was called before.

所以是的,现在我可以肯定地说你不需要退订:)

So yes, now I can say for sure you don't need to unsubscribe :)

这篇关于我应该取消订阅 Cold Observable 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!