collectAsync<T> static method

  1. @useResult
Future<Option<T>> collectAsync<T>(
  1. FutureOr<Option<T>> collector(
    1. U check<U>(
      1. Option<U> option
      )
    )
)

Encloses any number of operations, optionally returning early on None.

See collect for a synchronous version of this function.

Examples

final collected = await Option.collectAsync<int>((check) async {
  // This passes the check and `first` gets the value `2`
  final first = check(await Future.value(const Some(2)));

  // This fails the check and no value is returned from the collector
  final second = check(await Future.value(const None<int>()));

  // This is never reached
  return Some(first + second);
});

// prints "None"
print(collected);

Implementation

@useResult
static Future<Option<T>> collectAsync<T>(
  FutureOr<Option<T>> Function(U Function<U>(Option<U> option) check) collector,
) async {
  try {
    return await collector(<U>(option) {
      return switch (option) {
        Some(:final value) => value,
        None() => throw const _CheckException()
      };
    });
  } on _CheckException {
    return None<T>();
  }
}