sequenceList<A, B> function
- ImmutableList<
TaskEither< listA, B> >
Sequences a list of TaskEither
into a single TaskEither
that produces a list of results.
If any of the TaskEither
computations in the list results in a Left
,
the whole computation will short-circuit and return that Left
.
If all computations are successful (i.e., they all result in a Right
),
a single Right
containing a list of all the results is returned.
Example:
final taskEithers = il.ImmutableList<TaskEither<String, int>>([
TaskEither(() => Future.value(Right<String, int>(1))),
TaskEither(() => Future.value(Right<String, int>(2))),
TaskEither(() => Future.value(Right<String, int>(3))),
]);
final result = await sequenceList(taskEithers);
if (result is Right) {
print(result.value); // Expected output: [1, 2, 3]
}
Error handling example:
final taskEithers = il.ImmutableList<TaskEither<String, int>>([
TaskEither(() => Future.value(Right<String, int>(1))),
TaskEither(() => Future.value(Left<String, int>("Error"))),
TaskEither(() => Future.value(Right<String, int>(3))),
]);
final result = await sequenceList(taskEithers);
if (result is Left) {
print(result.value); // Expected output: "Error"
}
@param list The list of TaskEither
computations to be sequenced.
@return A Future
that resolves to an Either
containing either an error
or a list of results.
Implementation
Future<e.Either<A, il.ImmutableList<B>>> sequenceList<A, B>(
il.ImmutableList<TaskEither<A, B>> list) async {
final results = <B>[];
for (var taskEither in list) {
e.Either<A, B> result = await taskEither.value();
switch (result) {
case e.Left(value: var leftValue):
return e.Left<A, il.ImmutableList<B>>(leftValue);
case e.Right(value: var rightValue):
results.add(rightValue);
}
}
return e.Right(il.of(results));
}