combineResult<T extends Object> function
Combines an iterable of Results into one containing a list of their values.
If any Result is an Err, applies the onErr function to combine errors.
Implementation
Result<List<T>> combineResult<T extends Object>(
Iterable<Result<T>> results, {
@noFutures Err<List<T>> Function(List<Result<T>> allResults)? onErr,
}) {
// Fast path: when no aggregating error handler is configured we never need
// to keep the original list around — iterate the input directly and
// propagate the first Err immediately. Skips one List allocation per call.
if (onErr == null) {
final successes = <T>[];
for (final result in results) {
switch (result) {
case Ok(value: final value):
successes.add(value);
case final Err err:
return err.transfErr();
}
}
return Ok(successes);
}
// Slow path: onErr wants the full original list, so materialize once.
final asList = results.toList();
final successes = <T>[];
for (final result in asList) {
switch (result) {
case Ok(value: final value):
successes.add(value);
case final Err _:
return onErr(asList);
}
}
return Ok(successes);
}