Should I unsubscribe from Cold Observable?

别等时光非礼了梦想. 提交于 2019-12-07 05:22:14

问题


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


回答1:


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 :)




回答2:


Since Cold Observables are finite you dont have to unsubscribe.

Unsubscribe when:

  • Infinite Obesrvables, ex. interval()
  • If subscribed to (Subject, BehaviorSubject, ReplaySubject, AsyncSubject)

In case of ReplaySubject you should unsubscribe if it cache life time is not provided

In case of AsyncSubject you should unsubscribe if it is not completed

  • Websocket stream
  • Abstract control ex. valueChanges()
  • Renderer2.listen()
  • Events streams ex. formEvent()
  • NgRx Store

Do not unsubscribe when:

  • If stream is ending himself ex. of('1','2')
  • Router events, all Observables from Router are unsubscribing them self
  • AsyncPipe
  • Finite Observable ex. http.get()
  • EventEmmiter

Subscribe have to be unsubscribed if it would not hit complete or error.

If I am wrong or missing something please let me know. Thanks ;)




回答3:


It is definitely the best practice to free the used memory in javascript just like other programming languages.

Since you are using angular 2 you can use ngOnDestroy life cycle hook to achieve as this method is executed when the component loses its scope.

Assuming that you use a below snippet to subscribe to a data

subscription = this._http.getMethod('...')
                    .subscribe(response => this.responses = response,
                    error =>this.errorMessage =<any> error)

You should be using importing OnDestroy lifecycle hook from angular/core using an import statement.

import { OnDestroy } from '@angular/core'

implement OnDestroy in your component as

export class MyComponent implements onDestroy {
     .............


     ngOnDestroy() {
          this.subscription.unsubscribe();
     }

}


来源:https://stackoverflow.com/questions/42000535/should-i-unsubscribe-from-cold-observable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!