conditionWithTimeout static method
Periodically checks a condition until it is met or a timeout occurs.
This method immediately returns true if the condition is already met.
Otherwise, it sets up a periodic timer that checks the condition at
regular intervals defined by Constants.repeatConditionCheckInterval.
If the condition is met within the timeout duration, the method
returns true. If the timeout is reached before the condition is met,
it returns false.
Returns a Future<bool> that completes with the result of the condition check.
All timers are automatically cancelled when the future completes.
Implementation
static Future<bool> conditionWithTimeout(Duration timeout, bool Function() condition) async {
final completer = Completer<bool>();
// Immediately return true if the condition is already met
if (condition()) {
return true;
}
// Set up a periodic timer to check for the condition
final timer = Timer.periodic(Constants.repeatConditionCheckInterval, (_) {
if (condition()) {
completer.complete(true);
}
});
// Set a timeout timer
final timeoutTimer = Timer(timeout, () {
if (!completer.isCompleted) {
completer.complete(false);
}
});
return completer.future.then((value) {
timeoutTimer.cancel(); // Cancel the subscription
timer.cancel(); // Cancel the timer
return value;
});
}