简体   繁体   中英

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

do I need to unsubscribe?

Probably.

If you're designing a subject which will complete -- ie, if you intend to call client.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?

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