singleResponseFutureWithTimeout<R> function
Same as singleResponseFuture, but with required timeoutValue
,
this allows us not to require a nullable return value
Implementation
Future<R> singleResponseFutureWithTimeout<R>(
void Function(SendPort responsePort) action,
Duration timeout,
R timeoutValue) {
var completer = Completer<R>.sync();
var responsePort = RawReceivePort();
var timer = Timer(timeout, () {
responsePort.close();
completer.complete(timeoutValue);
});
var zone = Zone.current;
responsePort.handler = (response) {
responsePort.close();
timer.cancel();
zone.run(() {
_castComplete<R>(completer, response);
});
};
try {
action(responsePort.sendPort);
} catch (error, stack) {
responsePort.close();
timer.cancel();
// Delay completion because completer is sync.
scheduleMicrotask(() {
completer.completeError(error, stack);
});
}
return completer.future;
}