Should I unsubscribe from Cold Observable?

后端 未结 3 1694
误落风尘
误落风尘 2021-01-07 00:33

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

But if it\'s Cold Observable

3条回答
  •  悲哀的现实
    2021-01-07 01:09

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

    if i step inside of unsibscribe 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 dont need to unsubscribe :)

提交回复
热议问题