UNPKG

ix

Version:

The Interactive Extensions for JavaScript

46 lines (44 loc) 1.94 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fromEventPattern = void 0; const tslib_1 = require("tslib"); const memoize_js_1 = require("./operators/memoize.js"); const identity_js_1 = require("../util/identity.js"); const isiterable_js_1 = require("../util/isiterable.js"); const asyncsink_js_1 = require("./asyncsink.js"); const { isArray } = Array; function callOrApply(fn, args) { return isArray(args) ? fn(...args) : fn(args); } /** * Creates async-iterable from an event emitter by adding handlers for both listening and unsubscribing from events. * * @template TSource The type of elements in the event emitter. * @param {(handler: (...args: any[]) => void) => void} addHandler The function to add a listener to the source. * @param {(handler: (...args: any[]) => void) => void} removeHandler The function to remove a listener from the source. * @returns {AsyncIterableX<TSource>} An async-iterable which contains the data from the underlying events as wrapped by the handlers. */ function fromEventPattern(addHandler, removeHandler, resultSelector) { if (!(0, isiterable_js_1.isFunction)(resultSelector)) { resultSelector = identity_js_1.identity; } const sink = new asyncsink_js_1.AsyncSink(); const handler = (...args) => sink.write(callOrApply(resultSelector, args)); addHandler(handler); const loop = function () { return tslib_1.__asyncGenerator(this, arguments, function* () { try { for (let next; !(next = yield tslib_1.__await(sink.next())).done;) { yield yield tslib_1.__await(next.value); } } finally { removeHandler(handler); sink.end(); } }); }; return (0, memoize_js_1.memoize)()(loop()); } exports.fromEventPattern = fromEventPattern; //# sourceMappingURL=fromeventpattern.js.map