import { Observable } from '../Observable'; import { EmptyError } from './lastValueFrom'; // Reusing EmptyError from lastValueFrom /** * Converts an observable to a promise by subscribing to the observable, * and returning a promise that will resolve with the first value emitted * by the observable. The subscription is then immediately unsubscribed. * * If the observable stream completes before any values were emitted, the * returned promise will reject with {@link EmptyError}. * * If the observable stream emits an error, the returned promise will reject * with that error. * * @param source The observable to convert to a promise. * @return A promise that resolves with the first value from the observable, * or rejects with an error or EmptyError. */ export function firstValueFrom(source: Observable): Promise { return new Promise((resolve, reject) => { let _hasValue = false; const subscription = source.subscribe({ next: (value) => { _hasValue = true; resolve(value); subscription.unsubscribe(); // Unsubscribe immediately after first value }, error: reject, complete: () => { if (!_hasValue) { reject(new EmptyError()); } }, }); }); }