requestThrottle<T, P> function
Leading-edge throttle. Calls inside duration share the same result.
Implementation
RequestServiceWrapper<T, P> requestThrottle<T, P>(Duration duration) {
if (duration < Duration.zero) {
throw ArgumentError.value(duration, 'duration', 'Cannot be negative.');
}
return (next) {
DateTime? lastStartedAt;
Future<T>? shared;
return (params, context) {
final now = DateTime.now();
final last = lastStartedAt;
if (last != null && now.difference(last) < duration && shared != null) {
return raceCancellation(shared!, context.cancellationToken);
}
lastStartedAt = now;
final future = next(params, context);
shared = future;
return future;
};
};
}