[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 timeouttaketakeWhile, 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'

 

posted @ 2024-02-11 22:00  Zhentiw  阅读(116)  评论(0编辑  收藏  举报