import { ActorRef, EmittedFrom } from '.';
interface WaitForOptions { timeout: number;}
const defaultWaitForOptions: WaitForOptions = { timeout: 10_000 };
export function waitFor<TActorRef extends ActorRef<any, any>>( actorRef: TActorRef, predicate: (emitted: EmittedFrom<TActorRef>) => boolean, options?: Partial<WaitForOptions>): Promise<EmittedFrom<TActorRef>> { const resolvedOptions: WaitForOptions = { ...defaultWaitForOptions, ...options }; return new Promise((res, rej) => { let done = false; if (process.env.NODE_ENV !== 'production' && resolvedOptions.timeout < 0) { console.error( '`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.' ); } const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => { sub.unsubscribe(); rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`)); }, resolvedOptions.timeout);
const dispose = () => { clearTimeout(handle!); done = true; sub?.unsubscribe(); };
const sub = actorRef.subscribe({ next: (emitted) => { if (predicate(emitted)) { dispose(); res(emitted); } }, error: (err) => { dispose(); rej(err); }, complete: () => { dispose(); rej(new Error(`Actor terminated without satisfying predicate`)); } }); if (done) { sub.unsubscribe(); } });}