when<R> method

R when<R>({
  1. required R success(
    1. T result
    ),
  2. required R error(
    1. Object error,
    2. StackTrace? stackTrace
    ),
  3. required R inProgress(),
  4. required R idle(),
})

Provides several callbacks for handling common states of async data. It functions as a rudimentary form of pattern matching.

  • idle callback is used to match the initial state where the operation hasn't started yet.
  • inProgress is used to handle an ongoing async operation.
  • success is called with the finished successful result.
  • error is to be called when the operation has finished with an Exception, with an optional StackTrace.

Implementation

R when<R>({
  required R Function(T result) success,
  required R Function(Object error, StackTrace? stackTrace) error,
  required R Function() inProgress,
  required R Function() idle,
}) {
  if (this is _InProgress) {
    return inProgress();
  } else if (this is _Error) {
    final err = this as _Error;
    return error(err.error, err.stackTrace);
  } else if (this is _Success) {
    return success((this as _Success<T>).results);
  } else {
    return idle();
  }
}