Skip to content

Synchronising

Module Iterables.Chains

Chains are inherently asynchronous. If you’re working with several, there might be a need to synchronise them in some manner. This is a way of aggregating data into a common array or object.

combineLatestToArray

combineLatestToArray monitors two or more chains, storing values as they happen to an array. Whenever a new value is emitted, the whole array is sent out, containing current values from each source, or undefined if not yet emitted.

// Three chains
const sources = [ ch1, ch2, ch3 ];
// 'combined' will be an async generator
const combined = Chains.combineLatestToArray(sources);
for await (const v of combined) {
// v will be an array [ value1, value2, value3 ],
// with indexes corresponding to `sources`
}
// Execution continues when one of the sources finishes.

The tempo of this stream will be set by the fastest source stream. syncToArray in contrast has a pace determined by slowest source, only sending when each source has produce a new value compared to last time.

There are a few options to determine what happens when a source completes. See the API docs for more information. By default as soon as one source finishes, the combined stream finishes.

combineLatestToObject

combineLatestToObject is essentially the same as combineLatestToArray() however it returns an object of values rather than array.

const combined = Chains.combineLatestToObject({
a: ch1,
b: ch2,
c: ch3
});
for await (const v of combined) {
// v will be an object: { a, b, c }
// where each value will be the value from the
// corresponding source
}

syncToArray

syncToArray waits for all sources to produce a value, sending the combined results as an array.

After sending, it waits again for each source to send at least one value. This means that the pace of the combined result will be determined by the slowest source. In contrast combineToArray/combineToObject have their pace set by the fastest source.

// Three sources
const sources = [ ch1, ch2, ch3 ];
// 'synced' will be an async generator
const synced = Chains.syncToArray(sources);
for await (const v of synced) {
// v will be an array of values, corresponding to
// the indexes of 'sources'
}

As soon as one source finishes, the synchronised generator will finish. You can tweak the behaviour when sources end by providing options, documented here.