我应该退订“冷观测"吗? [英] Should I unsubscribe from Cold Observable?

查看:52
本文介绍了我应该退订“冷观测"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道从[Observable]中退订以防止内存泄漏是一种很好的做法.

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?

例如Http.get()

推荐答案

您不需要这样做,因为对于HTTP observable而言,在完成操作后立即调用complete.

You dont need to do it because for HTTP observable is calling complete is immediately after action is done.

从源代码来源我可以看到取消订阅时,该操作将在错误且完成时被调用.

From source code sources i can see that on 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 small experiment by adding unsubscribe with timeout

var subscription = this.http.get(`apiurl`)
            .subscribe(response => {
                setTimeout(function(){ 
                    debugger;
                    subscription.unsubscribe(); }, 30);
            });

如果我取消订阅

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

然后是this.closed == true,这意味着之前已取消订阅.

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

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

So yes now I can say for sure you dont need to unsubscribe :)

这篇关于我应该退订“冷观测"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆