listenFor method

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

Implementation

@useResult
RemoveListener listenFor({
  // ignore: avoid_positional_boolean_parameters
  void Function(bool)? onWaiting,
  void Function(T)? onComplete,
  void Function(Object?, StackTrace?)? 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:
        onWaiting?.call(true);
      case _EventType.end:
        onWaiting?.call(false);
      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();
}