简体   繁体   中英

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. 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.

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.

When you want to get that behavior you should use the observable you've got and share it + replay the last value. Good thing is, there's an operator for that: 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!

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.

You need to subscribe in order to get the value, else you'll just get an 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.

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

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