throttle static method
Future<void>
throttle(
- String tag,
- Duration duration,
- FutureEasyThrottleCallback onExecute, {
- FutureEasyThrottleCallback? onAfter,
Will execute onExecute
immediately and ignore additional attempts to
call throttle with the same tag
happens for the given duration
.
tag
is any arbitrary String, and is used to identify this particular
throttle operation in subsequent calls to throttle() or cancel().
duration
is the amount of time subsequent attempts will be ignored.
Implementation
static Future<void> throttle(
String tag,
Duration duration,
FutureEasyThrottleCallback onExecute, {
FutureEasyThrottleCallback? onAfter,
}) {
final throttled = _operations.containsKey(tag);
if (throttled) {
return _operations[tag]!.$2.future;
}
_operations[tag] = (
_FutureEasyThrottleOperation(
onExecute,
Timer(duration, () {
_operations[tag]?.$2.tryComplete();
_operations[tag]?.$1.timer.cancel();
final removed = _operations.remove(tag);
removed?.$1.onAfter?.call();
}),
onAfter: onAfter,
),
Completer(),
);
onExecute().then((_) {
_operations[tag]?.$2.tryComplete();
_operations.remove(tag);
});
return _operations[tag]?.$2.future ?? Future.value();
}