Debian Codegraph @

node/rxjs/src/internal/lastValueFrom.ts

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