singleResponseFuture<R> function

Future<R> singleResponseFuture<R>(
  1. void action(
    1. SendPort responsePort
    ),
  2. {Duration? timeout,
  3. R? timeoutValue}
)

Implementation

Future<R> singleResponseFuture<R>(void Function(SendPort responsePort) action,
    {Duration? timeout, R? timeoutValue}) {
  var completer = Completer<R>.sync();
  var responsePort = RawReceivePort();
  Timer? timer;
  var zone = Zone.current;
  responsePort.handler = (Object response) {
    responsePort.close();
    timer?.cancel();
    zone.run(() {
      _castComplete<R>(completer, response);
    });
  };
  if (timeout != null) {
    timer = Timer(timeout, () {
      responsePort.close();
      completer.complete(timeoutValue);
    });
  }
  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;
}