update method

Future<AsyncPhase<T>> update(
  1. Future<T> func(), {
  2. void onWaiting(
    1. T data
    )?,
  3. void onComplete(
    1. T data
    )?,
  4. void onError(
    1. Object e,
    2. StackTrace s
    )?,
})

Runs the provided asynchronous function and updates the phase.

The phase is updated to AsyncWaiting when the callback starts, and to AsyncComplete or AsyncError according to success or failure when the callback ends.

The onWaiting, onComplete, and onError callbacks are called when the asynchronous operation starts, completes successfully, or fails, respectively. However, note that errors occurring in those callbacks are not automatically handled.

Implementation

Future<AsyncPhase<T>> update(
  Future<T> Function() func, {
  void Function(T data)? onWaiting,
  void Function(T data)? onComplete,
  void Function(Object e, StackTrace s)? onError,
}) async {
  value = value.copyAsWaiting();
  onWaiting?.call(data);

  final phase = await AsyncPhase.from(
    func,
    // Avoids providing data as of this moment as fallback data
    // because it becomes stale if `value.data` is updated externally
    // while the callback is executed.
    //
    // ignore: avoid_redundant_argument_values
    fallbackData: null,
  );

  if (!_isDisposed) {
    if (phase case AsyncError(:final error, :final stackTrace)) {
      value = phase.copyWith(data);
      onError?.call(error, stackTrace);
    } else {
      value = phase;
      onComplete?.call(data);
    }
  }
  return value;
}