Sometimes, we want to get current value of RxJS Subject or Observable.
In this article, we’ll look at how to get current value of RxJS Subject or Observable.
How to get current value of RxJS Subject or Observable?
To get current value of RxJS Subject or Observable, we can use the first method.
For instance, we write
const observable = of("foo");
const hasValue = (value: any) => {
return value !== null && value !== undefined;
};
const getValue = <T>(observable: Observable<T>): Promise<T> => {
return observable.pipe(filter(hasValue), first()).toPromise();
};
//...
to create an of observable.
Then we create the getValue function that calls observable.pipe with the filter and first operators to get the first value from the observable that isn’t null or undefined.
And then we call toPromise to return a promise with the value returned by the observable.
Then in an async function, we write
const result = await getValue(observable);
to get the value.
Conclusion
To get current value of RxJS Subject or Observable, we can use the first method.