XSelect class

Async multiplexing - race multiple operations with automatic cancellation.

The cornerstone of reactive, event-driven applications. Race channels, timers, futures, and streams with automatic cleanup of losers. Essential for building responsive UIs and efficient event processing systems.

Core Concepts

  • First wins: The first operation to complete wins, all others are canceled
  • Automatic cleanup: Losing operations are properly canceled to prevent leaks
  • Type-safe: Each branch can return different types, unified by the result type
  • Composable: Easily combine different async sources in a single select

Usage Patterns

Responsive UI with timeout:

final result = await XSelect.run<String>((s) => s
  ..onRecvValue(dataChannel, (data) => 'got_data: $data')
  ..onTick(Ticker.every(Duration(seconds: 1)), () => 'heartbeat')
  ..onTimeout(Duration(seconds: 30), () => 'timeout_reached')
);

switch (result) {
  case 'timeout_reached':
    showTimeoutMessage();
  case String data when data.startsWith('got_data'):
    processData(data);
  case 'heartbeat':
    updateHeartbeat();
}

Multi-source event aggregation:

final event = await XSelect.run<AppEvent>((s) => s
  ..onStream(userInteractions, (e) => AppEvent.user(e))
  ..onStream(networkEvents, (e) => AppEvent.network(e))
  ..onRecvValue(backgroundTasks, (t) => AppEvent.background(t))
  ..onFuture(systemCheck(), (r) => AppEvent.system(r))
);

handleEvent(event);

Configuration reload with graceful fallback:

Future<Config> loadConfigWithFallback() async {
  return await XSelect.run<Config>((s) => s
    ..onFuture(loadFromServer(), (c) => c)
    ..onFuture(loadFromCache(), (c) => c)
    ..onTimeout(Duration(seconds: 5), () => Config.defaultConfig())
  );
}

Constructors

XSelect.new()

Properties

hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Methods

race<R>(Iterable<void Function(SelectBuilder<R> b)> competitors, {bool ordered = false}) Future<R>
Compose several builders into a single race. Useful to keep related branches grouped.
run<R>(void build(SelectBuilder<R>), {bool ordered = false}) Future<R>
Race multiple async operations - first to complete wins.
syncRace<R>(Iterable<void Function(SelectBuilder<R> b)> competitors, {bool ordered = false}) → R?
Synchronous variant of race. Returns immediately if any competitor exposes an Arm.immediate; otherwise returns null without subscribing.
syncRun<R>(void build(SelectBuilder<R> s), {bool ordered = false}) → R?
Non-blocking selection over immediate arms only (e.g. Arm.immediate). Returns null if no arm can fire synchronously.