[RxJS] firstValueFrom/lastValueFrom (convert observable to promise)
Converts an observable to a promise by subscribing to the observable, and returning a promise that will resolve as soon as the first value arrives from the observable. The subscription will then be closed.
WARNING: Only use this with observables you know will emit at least one value, OR complete. If the source observable does not emit one value or complete, you will end up with a promise that is hung up, and potentially all of the state of an async function hanging out in memory. To avoid this situation, look into adding something like timeout
, take
, takeWhile
, or takeUntil
amongst others.
import { interval, firstValueFrom } from 'rxjs';
async function execute() {
const source$ = interval(2000);
const firstNumber = await firstValueFrom(source$);
console.log(`The first number is ${ firstNumber }`);
}
execute();
// Expected output:
// 'The first number is 0'
lastValueFrom
import { interval, take, lastValueFrom } from 'rxjs';
async function execute() {
const source$ = interval(2000).pipe(take(10));
const finalNumber = await lastValueFrom(source$);
console.log(`The final number is ${ finalNumber }`);
}
execute();
// Expected output:
// 'The final number is 9'