Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS: BehaviorSubject unsubscribe

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

like image 952
Jeremy Thomas Avatar asked Sep 13 '17 17:09

Jeremy Thomas


1 Answers

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?

like image 118
Nicholas Tower Avatar answered Oct 07 '22 14:10

Nicholas Tower