Reputation: 376
Is it good practice to subscribe directly to Observable returned from method?
Will it be garbage collected before the callback method is called?
For example I have method in service:
get<City>(id): Observable<City> {
var url = this.baseUrl + "api/Cities/" + id;
return this.http.get<City>(url);
}
Then in component I have:
ngOnInit () {
this.cityService.get<City>(this.id)
.subscribe(result => {
this.city = result;
},
error => console.error(error));
}
The callback method can be called any time, even after 10 minutes, and the Observable is already out of scope.
So is it possible that in a bad scenario the returned Observable can be garbage collected before the city is assigned in the callback method?
Upvotes: 1
Views: 1278
Reputation: 501
Two cases:
Observable
, then the Subscription
finish cause the Observable complete()
, it can now be garbage collected after has executed his callbackObservable
, then the Subscription
has to finish manually by subs.unsubscribe()
. Until that the Subscription keep the reference over the Observable, so it cannot be garbage collected before the unsubscriptionThe method http.get
is a short live Observable so you are in the case 2. Both cases are fine according to the garbage collection.
Upvotes: 1
Reputation: 138297
As long as some piece of code can access an object, the object will not be garbage collected.
So yes, depending on it's implementation, the Observable could be gc'ed whilst some piece of code still holds a reference to the callback and can thus call it. However if the implementation is that way, there is no dependency between the observable and the callback, and thus the code would work totally fine. So thats not really a bad scenario.
I guess however that the Observable not only provides a .subscribe
method, but also some other properties to manage the callbacks happen. In that case, the code that will call back somewhen actually holds a reference to the Observable, which itself holds a reference to the callback somewhere. In that case, the callback will only be gc'ed if the observable got gc'ed, and that only happens if the code does not hold a reference anymore, e.g. if it stops producing new events.
Upvotes: 0