简体   繁体   中英

How does Angular store an observable not linked to a variable?

Imagine I wrote an observable expression in ngOnInit() hook like this:

ngOnInint(){
  this.httpClient.get('request-url').subscribe(response => {
      ...
    })
}

And after ngOnInit execution the function's context may be destructed if it hasn't been saved to a variable. But even though the observable is still handled by any value emit.

The question is: where and how does angular keep tracking for the observable if it hasn`t been saved to variable?

Even without variable, subscription is actually created and browser allocates memory for it. And subscription, of course, is referencing observable/subject. Even if component is removed from the page, subscription still exists and causes memory leak because garbage collector will not remove it. That is how javascript works and it is not Angular or rxjs issue.

GC algorithms decide to remove object in accordance with various conditions. For example, if this object has zero references to other resources and there is no references from other objects to this one.

That is why you should unsubscribe from observables when you don't need subscription anymore. Under the hood, when you call unsubscribe , Rxjs cleans up observable references what results in two things: further value emits will be not handled anymore and GC will be able to free memory in the nearest time.

In Angular, the best practice is to do that in the ngOnDestroy :

ngOnInit() {
  this.subscription = this.httpClient.get('request-url').subscribe(...)
}

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

And of course in order to do that, you need to assign subscription to a variable, because in other way you will be not able to call unsubscribe method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM