when<U> method

U when<U>(
  1. {required U waiting(
    1. T?
    ),
  2. required U complete(
    1. T
    ),
  3. required U error(
    1. T?,
    2. Object?,
    3. StackTrace?
    ),
  4. U initial(
    1. T?
    )?}
)

A method that returns a value returned from one of callback functions corresponding to the current phase of an asynchronous operation.

This method calls one of the callbacks, initial, waiting, complete or error, that matches the current phase.

e.g. The complete callback is called if the current phase is AsyncComplete.

All parameters other than initial are required. If initial is omitted when the current phase is AsyncInitial, the waiting callback is called instead.

If only some of the properties is needed, use whenOrNull.

Implementation

U when<U>({
  required U Function(T?) waiting,
  required U Function(T) complete,
  required U Function(T?, Object?, StackTrace?) error,
  U Function(T?)? initial,
}) {
  return switch (this) {
    AsyncInitial() => initial == null ? waiting(data) : initial(data),
    AsyncWaiting() => waiting(data),
    AsyncComplete() => complete(data as T),
    AsyncError() => error(data, _error, _stackTrace),
  };
}