@reactivex/ix-es2015-cjs
Version:
The Interactive Extensions for JavaScript
66 lines (64 loc) • 2.55 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.race = exports.RaceAsyncIterable = void 0;
const tslib_1 = require("tslib");
const asynciterablex_js_1 = require("./asynciterablex.js");
const withabort_js_1 = require("./operators/withabort.js");
const aborterror_js_1 = require("../aborterror.js");
const safeRace_js_1 = require("../util/safeRace.js");
function wrapPromiseWithIndex(promise, index) {
return promise.then((value) => ({ value, index }));
}
/** @ignore */
class RaceAsyncIterable extends asynciterablex_js_1.AsyncIterableX {
constructor(sources) {
super();
this._sources = sources;
}
[Symbol.asyncIterator](signal) {
return tslib_1.__asyncGenerator(this, arguments, function* _a() {
(0, aborterror_js_1.throwIfAborted)(signal);
const sources = this._sources;
const length = sources.length;
const iterators = new Array(length);
const nexts = new Array(length);
for (let i = 0; i < length; i++) {
const iterator = (0, withabort_js_1.wrapWithAbort)(sources[i], signal)[Symbol.asyncIterator]();
iterators[i] = iterator;
nexts[i] = wrapPromiseWithIndex(iterator.next(), i);
}
const next = (0, safeRace_js_1.safeRace)(nexts);
const { value: next$, index } = yield tslib_1.__await(next);
if (!next$.done) {
yield yield tslib_1.__await(next$.value);
}
const iterator$ = iterators[index];
// Cancel/finish other iterators
for (let i = 0; i < length; i++) {
if (i === index) {
continue;
}
const otherIterator = iterators[i];
if (otherIterator.return) {
otherIterator.return();
}
}
let nextItem;
while (!(nextItem = yield tslib_1.__await(iterator$.next())).done) {
yield yield tslib_1.__await(nextItem.value);
}
});
}
}
exports.RaceAsyncIterable = RaceAsyncIterable;
/**
* Propagates the async sequence that reacts first.
*
* @param {...AsyncIterable<T>[]} sources The source sequences.
* @return {AsyncIterable<T>} An async sequence that surfaces either of the given sequences, whichever reacted first.
*/
function race(...sources) {
return new RaceAsyncIterable(sources);
}
exports.race = race;
//# sourceMappingURL=race.js.map