UNPKG

@thi.ng/rstream

Version:

Reactive streams & subscription primitives for constructing dataflow graphs / pipelines

53 lines (52 loc) 1.2 kB
import { SEMAPHORE } from "@thi.ng/api/api"; import { State } from "./api.js"; import { stream } from "./stream.js"; const fromAsync = (src, opts) => stream(($stream) => { let active = true; (async () => { try { for await (let x of src) { if (!active) return; $stream.next(x); } $stream.done(); } catch (e) { $stream.error(e); } })(); return () => active = false; }, opts); async function* asAsync(src) { let resolve; let initial; const $newInitial = () => { return initial = new Promise(($resolve) => { resolve = $resolve; }); }; const promises = [$newInitial()]; src.subscribe({ next(x) { if (initial) { resolve(x); initial = void 0; } else promises.push(Promise.resolve(x)); }, done() { if (initial) { resolve(SEMAPHORE); initial = void 0; } else promises.push(Promise.resolve(SEMAPHORE)); } }); while (promises.length && src.getState() < State.ERROR) { const res = await promises.shift(); if (res === SEMAPHORE) break; if (!promises.length) promises[0] = $newInitial(); yield res; } } export { asAsync, fromAsync };