combineSync<T extends Object> function
Combines an iterable of Syncs into one containing a list of their values.
If any Sync contains an Err, applies the onErr function to combine
errors.
The input iterable is consumed exactly once, so it is safe to pass a single-pass iterable.
Implementation
Sync<List<T>> combineSync<T extends Object>(
Iterable<Sync<T>> syncs, {
@noFutures Err<List<T>> Function(List<Result<T>> allResults)? onErr,
}) {
// Materialize once: `isEmpty` and the subsequent `.map(...).toList()`
// would otherwise iterate the input twice, which loses every element on
// a single-pass iterable.
final list = syncs.toList(growable: false);
if (list.isEmpty) {
return Sync.okValue([]);
}
return Sync(() {
final results = list.map((s) => s.value).toList();
final combined = combineResult(results, onErr: onErr);
switch (combined) {
case Ok(value: final value):
return value;
case Err err:
throw err;
}
});
}