throttle method
Future<void>
throttle(
- Future<
void> function(), { - Duration duration = const Duration(milliseconds: 500),
- bool waitForFunction = true,
- String throttleIdentifier = '',
inherited
Execute given function and then block further executing of the same function for certain duration.
waitForFunction
if set to true it will wait if function finishes after provided duration delay, otherwise will finish immediately after given duration
Implementation
@protected
Future<void> throttle(
Future<void> Function() function, {
Duration duration = const Duration(milliseconds: 500),
bool waitForFunction = true,
String throttleIdentifier = '',
}) async {
if (_isThrottlingMap[throttleIdentifier] == true) return;
_isThrottlingMap[throttleIdentifier] = true;
final functionCompleter = Completer();
final throttleCompleter = Completer();
var durationFinished = false;
void completeThrottle() {
if (!throttleCompleter.isCompleted) {
_isThrottlingMap[throttleIdentifier] = false;
throttleCompleter.complete();
}
}
function().then(
(value) {
functionCompleter.complete();
if (durationFinished) completeThrottle();
},
onError: (error) {
functionCompleter.completeError(error);
if (durationFinished) completeThrottle();
},
);
Future.delayed(duration, () {
durationFinished = true;
if (!waitForFunction || functionCompleter.isCompleted) {
completeThrottle();
}
});
await Future.wait([
if (waitForFunction) functionCompleter.future,
throttleCompleter.future,
]);
}