UNPKG

1.1 kBJavaScriptView Raw
1import { AsyncSink } from './asyncsink';
2import { memoize } from './operators/memoize';
3/**
4 * Creates asnyc-iterable from an event emitter by adding handlers for both listening and unsubscribing from events.
5 *
6 * @export
7 * @template TSource The type of elements in the event emitter.
8 * @param {(handler: (...args: any[]) => void) => void} addHandler The function to add a listener to the source.
9 * @param {(handler: (...args: any[]) => void) => void} removeHandler The function to remove a listener from the source.
10 * @returns {AsyncIterableX<TSource>} An async-iterable which contains the data from the underlying events as wrapped by the handlers.
11 */
12export function fromEventPattern(addHandler, removeHandler) {
13 const sink = new AsyncSink();
14 const handler = (e) => sink.write(e);
15 addHandler(handler);
16 const yielder = async function* () {
17 for (let next; !(next = await sink.next()).done;) {
18 yield next.value;
19 }
20 removeHandler(handler);
21 sink.end();
22 };
23 return memoize()(yielder());
24}
25
26//# sourceMappingURL=fromeventpattern.mjs.map