asyncFlatMap<T> method

Future<Result<T>> asyncFlatMap<T>(
  1. FutureOr<Result<T>> transform(
    1. S value
    )
)

Chains another operation that returns a FutureOr<Result> sequentially.

If the current Result is a success, passes its value to the transform function, which returns a new Result (flattening the nested results). If the current Result is a failure, the operation short-circuits and returns the failure immediately.

Example:

Future<Result<Orders>> ordersResult = fetchUser()
    .asyncFlatMap((user) => repository.getOrders(user.id));

Implementation

Future<Result<T>> asyncFlatMap<T>(
  FutureOr<Result<T>> Function(S value) transform,
) async {
  final result = await this;

  return switch (result) {
    SuccessResult<S>(success: Success(:final value)) =>
      await transform(value),
    FailureResult<S>(failure: final failure) => Result.failure(failure),
  };
}