Categories
JavaScript Answers

How to Use await on an Rx js Observable?

Spread the love

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.

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *