rateLimit method
- String tag,
- Duration duration,
- VoidCallback onExecute, {
- VoidCallback? onAfter,
Will execute onExecute
immediately and record additional attempts to
call rateLimit with the same tag
happens until the given duration
has passed
when it will execute with the last attempt.
tag
is any arbitrary String, and is used to identify this particular rate limited
operation in subsequent calls to rateLimit() or cancel()
.
duration
is the amount of time until the subsequent attempts will be sent.
onAfter
is executed after the duration
has passed in which there were no rate limited calls.
Returns whether the operation was rate limited
Implementation
bool rateLimit(
String tag,
Duration duration,
VoidCallback onExecute, {
VoidCallback? onAfter,
}) {
final rateLimited = _rateLimitOperations.containsKey(tag);
if (rateLimited) {
_rateLimitOperations[tag]?.callback = onExecute;
_rateLimitOperations[tag]?.onAfter = onAfter;
return true;
}
final operation = _InnerOperation(
timer: Timer.periodic(duration, (Timer timer) {
final operation = _rateLimitOperations[tag];
if (operation != null) {
operation.callback();
if (operation.onAfter != null) {
operation.onAfter!();
}
operation.callback = () {};
operation.onAfter = null;
}
}),
callback: onExecute,
onAfter: onAfter,
);
_rateLimitOperations[tag] = operation;
onExecute();
return false;
}