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,
}) {
  switch (this) {
    case AsyncInitial(:final data):
      return initial == null ? waiting(data) : initial(data);
    case AsyncWaiting(:final data):
      return waiting(data);
    case AsyncComplete(:final data):
      return complete(data);
    case AsyncError(:final data, error: final e, stackTrace: final s):
      return error(data, e, s);
  }
}