简体   繁体   English

RxJS:BehaviorSubject取消订阅

[英]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: 和susbscirbe在他们看来像这样:

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

do I need to unsubscribe? 我需要取消订阅吗? What if I called client.getValue() ? 如果我调用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. 如果您正在设计一个将完成的主题 - 即,如果您打算调用client.complete() (或者如果您使用rxjs 4则调用client.onCompleted() ) - 那么这将自动拆除订阅。

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: 1)手动:

When you call .subscribe, you get back a subscription object. 当你调用.subscribe时,你会收到一个订阅对象。 If you call .unsubscribe() on it ( .dispose() in rxjs 4), you will unsubscribe. 如果你在它.dispose()调用.unsubscribe() (rxjs 4中的.dispose() ),你将取消订阅。 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. 2)基于另一个可观察的自动。 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. Observable有一个.takeUntil运算符,您可以将其传递给另一个observable。 When that second observable emits a value, it will do the unsubscription for you. 当第二个observable发出一个值时,它会为你取消订阅。 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() 如果我调用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? 但是,在不利方面,如果您不想看到价值何时发生变化,您为什么要使用行为主题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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