singleResultFuture<R> function

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

Creates a Future, and a SendPort that can be used to complete that future.

Calls action with the response SendPort, then waits for someone to send a future result on that port using sendFutureResult. The returned Future is completed with the future result sent on the port.

If action throws, which it shouldn't, the returned future is completed with that error, unless someone manages to send a message on the port before action throws.

If timeout is supplied, it is used as a limit on how long it can take before the message is received. If a message isn't received in time, the onTimeout is called, and the future is completed with the result of that call instead. If onTimeout is omitted, it defaults to throwing a TimeoutException.

Implementation

Future<R> singleResultFuture<R>(void Function(SendPort responsePort) action,
    {Duration? timeout, FutureOr<R> Function()? onTimeout}) {
  var completer = Completer<R>.sync();
  var port = singleCompletePort<R, List<Object?>>(completer,
      callback: receiveFutureResult, timeout: timeout, onTimeout: onTimeout);
  try {
    action(port);
  } catch (e, s) {
    // This should not happen.
    sendFutureResult(Future.error(e, s), port);
  }
  return completer.future;
}