This function allows you to multiplex multiple asynchronous generators iterables into one.
Items from all iterables will be streamed to resulting one as soon as they come from source iterable.
And last but not least, you can add new iterables to multiplexer after it was created!
Example:
const gen = <a>(as: readonly a[], name: string, pause: number) => async function* () {
await wait(pause);
for (const a of as) {
yield `${name}: ${a}`;
await wait(100);
}
};
const foo = gen(['1', '2', '3', '4', '5', '6'], 'foo', 100);
const bar = gen(['a', 'b', 'c', 'd', 'e', 'f'], 'bar', 50);
const baz = gen(['Q', 'W', 'E', 'R', 'T', 'Y'], 'baz', 0);
const multiplexed = agm(foo(), bar());
(async () => {
for await (const x of multiplexed) {
console.log(x);
}
})();
multiplexed(baz());
// Output:
//
// 'baz: Q'
// 'bar: a'
// 'foo: 1'
// 'baz: W'
// 'bar: b'
// 'foo: 2'
// 'baz: E'
// 'bar: c'
// 'foo: 3'
// 'baz: R'
// 'bar: d'
// 'foo: 4'
// 'baz: T'
// 'bar: e'
// 'foo: 5'
// 'baz: Y'
// 'bar: f'
// 'foo: 6'
MIT