555195b8638f0dc26db6714e620533eff71f3745b8e07514405695cae8a89c93c6c62aaae815151c093b510a99c4b8673d454353a2527dbe4b6e9f671df838 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { Observable } from './Observable';
  2. import { EmptyError } from './util/EmptyError';
  3. import { SafeSubscriber } from './Subscriber';
  4. export interface FirstValueFromConfig<T> {
  5. defaultValue: T;
  6. }
  7. export function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>;
  8. export function firstValueFrom<T>(source: Observable<T>): Promise<T>;
  9. /**
  10. * Converts an observable to a promise by subscribing to the observable,
  11. * and returning a promise that will resolve as soon as the first value
  12. * arrives from the observable. The subscription will then be closed.
  13. *
  14. * If the observable stream completes before any values were emitted, the
  15. * returned promise will reject with {@link EmptyError} or will resolve
  16. * with the default value if a default was specified.
  17. *
  18. * If the observable stream emits an error, the returned promise will reject
  19. * with that error.
  20. *
  21. * **WARNING**: Only use this with observables you *know* will emit at least one value,
  22. * *OR* complete. If the source observable does not emit one value or complete, you will
  23. * end up with a promise that is hung up, and potentially all of the state of an
  24. * async function hanging out in memory. To avoid this situation, look into adding
  25. * something like {@link timeout}, {@link take}, {@link takeWhile}, or {@link takeUntil}
  26. * amongst others.
  27. *
  28. * ## Example
  29. *
  30. * Wait for the first value from a stream and emit it from a promise in
  31. * an async function
  32. *
  33. * ```ts
  34. * import { interval, firstValueFrom } from 'rxjs';
  35. *
  36. * async function execute() {
  37. * const source$ = interval(2000);
  38. * const firstNumber = await firstValueFrom(source$);
  39. * console.log(`The first number is ${ firstNumber }`);
  40. * }
  41. *
  42. * execute();
  43. *
  44. * // Expected output:
  45. * // 'The first number is 0'
  46. * ```
  47. *
  48. * @see {@link lastValueFrom}
  49. *
  50. * @param source the observable to convert to a promise
  51. * @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value
  52. */
  53. export function firstValueFrom<T, D>(source: Observable<T>, config?: FirstValueFromConfig<D>): Promise<T | D> {
  54. const hasConfig = typeof config === 'object';
  55. return new Promise<T | D>((resolve, reject) => {
  56. const subscriber = new SafeSubscriber<T>({
  57. next: (value) => {
  58. resolve(value);
  59. subscriber.unsubscribe();
  60. },
  61. error: reject,
  62. complete: () => {
  63. if (hasConfig) {
  64. resolve(config!.defaultValue);
  65. } else {
  66. reject(new EmptyError());
  67. }
  68. },
  69. });
  70. source.subscribe(subscriber);
  71. });
  72. }