runIfAllowed<T> method

Future<T?> runIfAllowed<T>(
  1. Future<T> action()
)

Executes the provided action if a token is available, otherwise returns null.

This is a convenience method that combines tryConsume with executing an action. If a token is available, it will be consumed and the action will be executed. If no token is available, null will be returned without executing the action.

Example:

final result = await limiter.runIfAllowed(() async {
  return await api.sendMessage(text);
});
// result will be null if rate limited

Implementation

Future<T?> runIfAllowed<T>(Future<T> Function() action) async {
  if (await tryConsume()) {
    return await action();
  }
  return null;
}