To use await
with Rxjs observables, we’ve to convert it to a promise first.
To do that, we can use the firstValueFrom
or lastValueFrom
functions.
firstValueFrom
returns promise that resolves to the first value of an observable.
lastValueFrom
returns promise that resolves to the last value of an observable.
For instance, we can use it by writing:
import { firstValueFrom, lastValueFrom, of } from "rxjs";
(async () => {
const myObservable = of(1, 2, 3);
const first = await firstValueFrom(myObservable);
console.log(first);
const last = await lastValueFrom(myObservable);
console.log(last);
})();
We have the myObservable
observable, which we created by calling the of
function.
of
returns an observable that emits the arguments that we pass in sequentially.
Then we call firstValueFrom
with myObservable
.
Then we see that first
is 1.
Next, we call lastValueFrom
with myObservable
.
The last
is 3.