conditionWithSubscription static method

Future<bool> conditionWithSubscription(
  1. Duration timeout,
  2. Completer<bool> completer,
  3. StreamSubscription subscription
)

Waits for a condition to be met using a StreamSubscription, with a timeout.

This utility function is especially useful if you need to wait for something to happen on a stream, for example for a certain event to happen on an event bus.

This method sets up a timer that will complete the completer with false if the timeout is reached before the condition is met. The subscription is expected to complete the completer with true when the condition is met.

Returns a Future<bool> that completes with the result of the condition check.

The subscription and timer are automatically cancelled when the future completes.

Implementation

static Future<bool> conditionWithSubscription(
    Duration timeout, Completer<bool> completer, StreamSubscription subscription) {
  // Set a timeout to complete with false if the event doesn't occur
  final timeoutTimer = Timer(timeout, () {
    if (!completer.isCompleted) {
      completer.complete(false);
    }
  });

  return completer.future.then((value) {
    subscription.cancel(); // Cancel the subscription
    timeoutTimer.cancel(); // Cancel the timer
    return value;
  });
}