Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  143] [ 6]  / answers: 1 / hits: 25441  / 7 Years ago, wed, september 13, 2017, 12:00:00

I am very new to observables am worried about memory leaks. If I create the following:



private client =  new BehaviorSubject();
clientStream$ = this.client.asObservable();


and susbscirbe to them in views like so:



this.clientService.clientStream$.subscribe(
client => {
this.client = client;
}
}


do I need to unsubscribe? What if I called client.getValue()?


More From » rxjs

 Answers
23

do I need to unsubscribe?




Probably.



If you're designing a subject which will complete -- ie, if you intend to callclient.complete() (or client.onCompleted() if you're using rxjs 4) -- then this will tear down the subscriptions automatically.



But often times, your behavior subject will be in some service which persists, and you don't want it to complete. In that case, you will need to unsubscribe. There are two ways you can unsubscribe:



1) Manually:



When you call .subscribe, you get back a subscription object. If you call .unsubscribe() on it (.dispose() in rxjs 4), you will unsubscribe. For example:



const subscription = this.clientService.clientStream$
.subscribe(client => this.client = client);

setTimeout(() => subscription.unsubscribe(), 10000); // unsubscribe after 10 seconds


2) Automatically, based on another observable. If you're using observables often in your application, you will probably find this approach to be very convenient.



Observables have a .takeUntil operator, which you can pass in another observable to. When that second observable emits a value, it will do the unsubscription for you. This lets you describe up front what conditions should tear down your observable. For example:



this.clientService.clientStream$
.takeUntil(Observable.timer(10000))
.subscribe(client => this.client = client);



What if I called client.getValue()




That will synchronously give you the current value. You're not subscribing at all. On the up side, this means you won't need to unsubscribe. But on the downside, why are you using a behavior subject if you're not interested in seeing when the value changes?


[#56490] Monday, September 11, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loganl

Total Points: 424
Total Questions: 86
Total Answers: 112

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;