getStreamFirstResultInTimeLimit<T> function

Future<T?> getStreamFirstResultInTimeLimit<T>(
  1. Stream<T> stream,
  2. Duration timeout
)

Returns the first result from a stream in a time limit.

Arguments:

  • stream: The stream from which to obtain the result.
  • timeout: The time limit in milliseconds.

Returns:

The first result from the stream, or throws an exception if no result is obtained within the timeout.

Example:

// Creates a stream that emits numbers after 1 second
Stream<int> generateNumbers() async* {
  await Future.delayed(Duration(seconds: 1));
  yield 10;
}

// Gets the first result of the stream in a time limit of 2 seconds
Future<int> firstResult = getStreamFirstResultInTimeLimit(generateNumbers(), 2000);

// Handles the exception that can be thrown if no result is obtained within the time limit
try {
  // Prints the first result
  print(await firstResult);
} catch (e) {
  // Handles the exception
  print(e);
}

Output:

10

Implementation

Future<T?> getStreamFirstResultInTimeLimit<T>(
  Stream<T> stream,
  Duration timeout,
) async {
  // Creates a variable to store the first result
  T? firstResult;

  // Subscribes to the stream
  final subscription = stream.listen((event) {
    // If this is the first result, stores it
    firstResult ??= event;
  });

  // Starts a timer to cancel the subscription after the timeout
  Timer(timeout, subscription.cancel);

  // Waits for the stream to finish emitting events or for the timeout to expire
  await Future<void>.delayed(timeout);

  // If a result was obtained, returns it
  if (firstResult != null) {
    return firstResult;
  } else {
    // If no result was obtained, throws an exception
    throw TimeoutException('No result obtained within the timeout');
  }
}