waitForEvent<T> method

Future<T?> waitForEvent<T>(
  1. dynamic responseHandler(
    1. T
    ), {
  2. Duration? timeout = const Duration(seconds: 5),
})

Implementation

Future<T?> waitForEvent<T>(Function(T) responseHandler, {Duration? timeout = const Duration(seconds: 5)}) {
  late final StreamSubscription subscription;
  final Completer<T?> completer = Completer();
  subscription = listen((event) {
    if (event.runtimeType == T) {
      final result = responseHandler(event);
      completer.complete(result);
    }
    subscription.cancel();
  });
  if (timeout != null) {
    return completer.future.timeout(
      timeout,
      onTimeout: () {
        subscription.cancel();
        return Future.error(TimeoutException('No response received for ${T.toString} in ${timeout.inSeconds} seconds'));
      },
    );
  } else {
    return completer.future;
  }
}