@reactivex/ix-esnext-esm
Version:
The Interactive Extensions for JavaScript
52 lines (50 loc) • 1.81 kB
JavaScript
import { AsyncIterableX } from './asynciterablex.js';
import { wrapWithAbort } from './operators/withabort.js';
import { throwIfAborted } from '../aborterror.js';
import { safeRace } from '../util/safeRace.js';
// eslint-disable-next-line @typescript-eslint/no-empty-function
const NEVER_PROMISE = new Promise(() => { });
function wrapPromiseWithIndex(promise, index) {
return promise
.then(({ value, done }) => ({ value, done, index }))
.catch((error) => ({ error, index }));
}
/** @ignore */
export class MergeAsyncIterable extends AsyncIterableX {
_source;
constructor(source) {
super();
this._source = source;
}
async *[Symbol.asyncIterator](signal) {
throwIfAborted(signal);
const length = this._source.length;
const iterators = new Array(length);
const nexts = new Array(length);
let active = length;
for (let i = 0; i < length; i++) {
const iterator = wrapWithAbort(this._source[i], signal)[Symbol.asyncIterator]();
iterators[i] = iterator;
nexts[i] = wrapPromiseWithIndex(iterator.next(), i);
}
while (active > 0) {
const next = await safeRace(nexts);
if (next.hasOwnProperty('error')) {
throw next.error;
}
else if (next.done) {
nexts[next.index] = NEVER_PROMISE;
active--;
}
else {
const iterator$ = iterators[next.index];
nexts[next.index] = wrapPromiseWithIndex(iterator$.next(), next.index);
yield next.value;
}
}
}
}
export function merge(source, ...args) {
return new MergeAsyncIterable([source, ...args]);
}
//# sourceMappingURL=merge.js.map