Select in Dart

Our example demonstrates how to use Futures and async/await to handle multiple asynchronous operations in Dart. This is similar to the concept of selecting across multiple channels in other languages.

import 'dart:async';

Future<void> main() async {
  // For our example we'll work with two Futures.
  final future1 = Future<String>.delayed(
    Duration(seconds: 1),
    () => 'one',
  );
  final future2 = Future<String>.delayed(
    Duration(seconds: 2),
    () => 'two',
  );

  // We'll use Future.any to await both of these values
  // simultaneously, printing each one as it arrives.
  for (int i = 0; i < 2; i++) {
    final result = await Future.any([
      future1.then((value) => {'future1': value}),
      future2.then((value) => {'future2': value}),
    ]);
    
    if (result.containsKey('future1')) {
      print('received ${result['future1']}');
    } else if (result.containsKey('future2')) {
      print('received ${result['future2']}');
    }
  }
}

In this example, we create two Futures that will complete after different durations, simulating asynchronous operations like network requests.

We use Future.any to wait for either of the Futures to complete. This is similar to the select statement in other languages, allowing us to handle whichever operation completes first.

The for loop runs twice, ensuring we handle both Futures even though they complete at different times.

To run the program, save it as futures_example.dart and use the Dart CLI:

$ dart run futures_example.dart
received one
received two

Note that the total execution time is only about 2 seconds since both the 1 and 2 second delays execute concurrently.

This example demonstrates how Dart handles concurrent operations using Futures and async/await, providing a powerful way to manage asynchronous code.