next<T extends Object> method

Future<T> next<T extends Object>({
  1. bool where(
    1. T event
    )?,
  2. Duration timeout = const Duration(seconds: 5),
})

Wait for the next event assignable to T that satisfies where.

A zero timeout disables the timeout and waits until an event or dispose.

Implementation

Future<T> next<T extends Object>({
  bool Function(T event)? where,
  Duration timeout = const Duration(seconds: 5),
}) {
  _ensureOpen();
  if (timeout.isNegative) {
    throw ArgumentError.value(timeout, 'timeout', 'must not be negative');
  }

  final completer = Completer<Object>.sync();
  late final _RuntimeEventWaiter waiter;
  waiter = _RuntimeEventWaiter(
    matches: (event) => event is T && (where?.call(event) ?? true),
    completer: completer,
  );
  _waiters.add(waiter);

  Future<Object> future = completer.future;
  if (timeout != Duration.zero) {
    future = future.timeout(
      timeout,
      onTimeout: () {
        _waiters.remove(waiter);
        throw RuntimeEventWaitTimeoutException(T, timeout);
      },
    );
  }

  return future.then<T>((event) => event as T);
}