In my project, I use BehaviorSubject
s as data stores to store the state of my application.
I need only the current value that is currently held in the BehaviorSubject
store, and don't need to subscribe to future values that can be emitted through the behavior subject.
I found few implementations of how to do this: using pipe(take(1))
, firstValueFrom
and .value
.
Do all work the same way and read the current value in the BehaviorSubject store? What are the differences between them, if any?
private myStore$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
// reading only one current value using take(1):
this.myStore$.pipe(take(1))
.subscribe(value => console.log('current value = ', value));
// reading only one current value using firstValueFrom:
const value = await firstValueFrom(this.myStore$);
console.log('current value = ', value);
// reading only one current value using this.myStore$.value:
const value = this.myStore$.value;
console.log('current value = ', value);
first
vstake(1)
, see https://mcmap.net/q/115854/-take-1-vs-first – LatishalatitudemyStore$.value
is synchronous, you don't need any async constructs to access it. Thetake(1)
variant is asynchronous but it is still using observables (recommended approach in my opinion if you want to go with async access for this value. Check Aldin's comment abouttake(1)
vsfirst()
and see which one best fits your requirements) and thefirstValueFrom
will give you a promise object that needs to be handled using eitherawait
like in your snippet, or usingthen
. – Secretion