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.