Debian Codegraph @

node/rxjs/src/internal/firstValueFrom.ts

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