Created
May 23, 2021 04:26
-
-
Save munro/4093387aae3f18136d41c4464f571c61 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export async function* createAsyncGenerator<T>( | |
createResource: (opts: { send: (value: T) => void, close: () => void }) => void, | |
reconnect?: () => Promise<void> | |
): AsyncGenerator<T, void, undefined> { | |
while (true) { | |
let closed = false; | |
let buffer: T[] = []; | |
let bufferHasData = createEvent(); | |
createResource({ | |
send(data) { | |
buffer.push(data); | |
bufferHasData.set(); | |
bufferHasData = createEvent(); | |
}, | |
close() { | |
closed = true; | |
bufferHasData.set(); | |
} | |
}); | |
while (!closed) { | |
yield* buffer; | |
await bufferHasData.wait; | |
} | |
if (typeof reconnect !== "undefined") { | |
await reconnect(); | |
} | |
} | |
} | |
export function createEvent() { | |
let resolve: ((value?: void) => void) | true | null = null; | |
return { | |
set() { | |
if (resolve === null || resolve === true) { | |
resolve = true; | |
} else { | |
resolve(); | |
} | |
}, | |
wait: new Promise<void>(r => { | |
if (resolve === true) { | |
r(); | |
} else { | |
resolve = r; | |
} | |
}) | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment