run<R> static method

Future<R> run<R>(
  1. void build(
    1. SelectBuilder<R>
    ), {
  2. bool ordered = false,
})

Race multiple async operations - first to complete wins.

Build a selection of async operations using the builder pattern. The first operation to complete determines the result, and all other operations are automatically canceled.

Parameters:

  • build: Builder function to configure the selection branches
  • onTimeout: Optional global timeout for the entire selection
  • ordered: If true, evaluates branches in order; if false, uses fairness rotation

Example - Event-driven architecture:

// WebSocket server with graceful shutdown and health checks
class WebSocketManager {
  final _commands = XChannel.mpsc<ServerCommand>(capacity: 100);
  final _health = Ticker.every(Duration(seconds: 30));

  Future<void> eventLoop() async {
    while (true) {
      final action = await XSelect.run<String>((s) => s
        ..onRecvValue(_commands, (cmd) => _handleCommand(cmd))
        ..onTick(_health, () => 'health_check')
        ..onStream(websocketStream, (msg) => _handleWebSocket(msg))
        ..onTimeout(Duration(minutes: 5), () => 'idle_timeout')
      );

      if (action == 'idle_timeout') break;
      if (action == 'shutdown') break;
      // Continue processing...
    }
  }
}

See also:

  • SelectBuilder for available operations
  • Ticker for timer-based operations
  • XChannel for channel-based communication

Implementation

static Future<R> run<R>(
  void Function(SelectBuilder<R>) build, {
  bool ordered = false,
}) async {
  final b = SelectBuilder<R>();
  build(b);
  if (ordered) b.ordered();
  return b.run();
}