listenFor method

  1. @useResult
RemoveListener listenFor({
  1. void onWaiting(
    1. T data
    )?,
  2. void onComplete(
    1. T data
    )?,
  3. void onError(
    1. Object e,
    2. StackTrace s
    )?,
})

Implementation

@useResult
RemoveListener listenFor({
  void Function(T data)? onWaiting,
  void Function(T data)? onComplete,
  void Function(Object e, StackTrace s)? onError,
}) {
  // ignore: prefer_asserts_with_message
  assert(ChangeNotifier.debugAssertNotDisposed(this));

  if (onComplete == null && onWaiting == null && onError == null) {
    return () {};
  }

  _eventStreamController ??= StreamController<_Event<T>>.broadcast();
  final subscription = _eventStreamController?.stream.listen((event) {
    switch (event.type) {
      case _EventType.start:
        final phase = event.phase as AsyncWaiting<T>;
        onWaiting?.call(phase.data as T);
      case _EventType.success:
        final phase = event.phase as AsyncComplete<T>;
        onComplete?.call(phase.data);
      case _EventType.error:
        final phase = event.phase as AsyncError<T>;
        onError?.call(phase.error, phase.stackTrace);
    }
  });

  return () => subscription?.cancel();
}