waitForEvent<T> method
Future<T?>
waitForEvent<T>(
- dynamic responseHandler(
- T
- 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;
}
}