waitUntil method
Waits for an update that satisfies a predicate function with timeout.
The predicate function receives the context and should return true if the update should be accepted.
Parameters:
predicate
: Function that determines if an update should be accepted.timeout
: Custom timeout for this wait operation.otherwise
: Optional function called for updates that don't match the predicate.
Example:
await ctx.reply('Send me a number:');
final numberCtx = await conversation.waitUntil(
(ctx) {
final text = ctx.text;
return text != null && int.tryParse(text) != null;
},
timeout: Duration(minutes: 3),
otherwise: (ctx) async {
await ctx.reply('Please send a valid number.');
},
);
final number = int.parse(numberCtx.text!);
await numberCtx.reply('You sent: $number');
Implementation
Future<CTX> waitUntil(
bool Function(CTX ctx) predicate, {
Duration? timeout,
Future<void> Function(CTX ctx)? otherwise,
}) async {
final deadline = timeout != null ? DateTime.now().add(timeout) : null;
CTX ctx;
do {
final remainingTime = deadline?.difference(DateTime.now());
if (remainingTime != null && remainingTime.isNegative) {
throw ConversationTimeoutException(_conversationName);
}
ctx = await wait(remainingTime);
if (!predicate(ctx) && otherwise != null) {
await otherwise(ctx);
}
} while (!predicate(ctx));
return ctx;
}