collect method
Convert an Iterable<Result<T, E>>
to a Result<Iterable<T>, E>
.
If there is an Err
in the iterable the first Err
is returned.
Basic usage
final list = <Result<int, String>>[
Ok(4),
Ok(7),
Ok(2),
Err('first'),
Ok(9),
Err('second'),
];
final resultList = list.collect();
expect(resultList, ErrIterable<int>, String>('first'));
final list = <Result<int, String>>[Ok(1), Ok(2), Ok(3), Ok(4)];
final resultList = list.collect();
expect(resultList.unwrap(), [1, 2, 3, 4]);
Implementation
Result<Iterable<T>, E> collect() {
try {
final error = firstWhere(
(Result<T, E> result) => result.isErr,
).unwrapErr();
return Err(error);
} catch (_) {
return Ok(map((Result<T, E> result) => result.unwrap()));
}
}