简体   繁体   English

如何使用 Observable 订阅行为主体

[英]How to Subscribe a Behavior Subject with an Observable

I have a scenario where I want to get the current value of an Observable variable on a user click which is a Store Selector.我有一个场景,我想在用户单击时获取 Observable 变量的当前值,这是一个商店选择器。 As per the accepted question of This Question I have to use a Behavior Subject.根据此问题的已接受问题,我必须使用行为主题。 But I'm getting ab Observable value from the Store selector.但是我从 Store 选择器中获得了 ab Observable 值。

Now, the problem is how to assign that Observable value to the Behavior Subject to use the current value of Behavior Subject at any time in the App.现在,问题是如何将该 Observable 值分配给 Behavior Subject 以在 App 中随时使用 Behavior Subject 的当前值。

When you want to get that behavior you should use the observable you've got and share it + replay the last value.当您想要获得该行为时,您应该使用您拥有的 observable 并分享它 + 重播最后一个值。 Good thing is, there's an operator for that: shareReplay .好消息是,有一个操作符: shareReplay

Important note: define the params of shareReplay otherwise you'll replay an infinite number of values and if no one listen to the observable anymore.. It'll still be kept open!重要提示:定义 shareReplay 的参数,否则你将重播无限数量的值,如果没有人再听可观察的......它仍然会保持打开状态!

So do the following:因此,请执行以下操作:

const replayedObs$ = originalObs$.pipe(
  shareReplay({ bufferSize: 1, refCount: true })
)

this way you'll only get the latest value when you subscribe AND if no one listen to the replayedObs$ anymore it'll be closed.这样你只会在订阅时获得最新的值,如果没有人再听replayedObs$它将被关闭。

You need to subscribe in order to get the value, else you'll just get an Observable .您需要订阅才能获得价值,否则您只会获得一个Observable

Here's an example:下面是一个例子:

subject: BehaviorSubject<any> = new BehaviorSubject('initial value'); 

  showVal()
  {
    this.subject.subscribe(x => this.val = x);
  }

And here is a StackBlitz demo.是一个 StackBlitz 演示。

The solution to your problem would be this:您的问题的解决方案是这样的:

const observable = of(true);
const behaviorSubject = new BehaviorSubject(false);

observable.subscribe(res => behaviorSubject.next(res));

console.log(behaviorSubject.value);

https://stackblitz.com/edit/rxjs-xd4mpp https://stackblitz.com/edit/rxjs-xd4mpp

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

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