Should I unsubscribe from the Cold Observable?

I know that a good recommendation is to unsubscribe from Observable to prevent memory leaks .

But if he is a Cold Observable, should I unsubscribe from him?

For example, the one returned by Http.get()

+5
source share
3 answers

You do not need to do this, because for an HTTP-observable, the call ends immediately after the action is completed.

From the sources of the sources, I see that when unsubscribing, an error is caused and terminates.

  protected _error(err: any): void { this.destination.error(err); this.unsubscribe(); } protected _complete(): void { this.destination.complete(); this.unsubscribe(); } 

I went ahead and did a little experiment by adding unsubscribe with a timeout

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

if i'm inside unsibscribe on

  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 unsubscribing.

So, yes, now I can say that you do not need to unsubscribe :)

+2
source

This is by far the best way to free up used memory in javascript, like other programming languages.

Since you are using angular 2, you can use the ngOnDestroy lifecycle hook to achieve since this method is executed when the component loses its scope.

Assuming you are using the snippet below to subscribe to data

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

You should use the import OnDestroy lifecycle from angular / core using the import statement.

 import { OnDestroy } from '@angular/core' 

implement OnDestroy in your component as

 export class MyComponent implements onDestroy { ............. ngOnDestroy() { this.subscription.unsubscribe(); } } 
0
source

Since Cold Observables are finite, you do not need to unsubscribe.

Unsubscribe when:

  • Infinite Obesrvables, ex. Interval()
  • If subscribing to (Subject, BehaviorSubject, ReplaySubject, AsyncSubject)

In case of ReplaySubject you should unsubscribe if cache lifetime is not specified

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

  • Web socket stream
  • Abstract control ex. valueChanges ()
  • Renderer2.listen ()
  • Ex stream events formEvent ()
  • NgRx Store

Do not unsubscribe when:

  • If the thread ends, it is itself from ('1', '2')
  • Router Events, all Observed from the Router unsubscribe themselves
  • Asyncpipe
  • Surely Observed ex. http.get ()
  • Eventemmiter

The subscription must be unsubscribed if it is not completed or an error.

If I am mistaken or missed something, please let me know. Thanks ;)

0
source

Source: https://habr.com/ru/post/1263728/


All Articles