2024-01-15 15:26:13 +00:00
|
|
|
import 'package:flutter_hooks/flutter_hooks.dart';
|
|
|
|
|
|
|
|
|
|
/// Throttles function calls with the [interval] provided.
|
|
|
|
|
/// Also make sures to call the last Action after the elapsed interval
|
|
|
|
|
class Throttler {
|
|
|
|
|
final Duration interval;
|
|
|
|
|
DateTime? _lastActionTime;
|
|
|
|
|
|
|
|
|
|
Throttler({required this.interval});
|
|
|
|
|
|
2024-12-05 02:33:46 +05:30
|
|
|
T? run<T>(T Function() action) {
|
2025-07-25 08:07:22 +05:30
|
|
|
if (_lastActionTime == null || (DateTime.now().difference(_lastActionTime!) > interval)) {
|
2024-12-05 02:33:46 +05:30
|
|
|
final response = action();
|
2024-01-15 15:26:13 +00:00
|
|
|
_lastActionTime = DateTime.now();
|
2024-12-05 02:33:46 +05:30
|
|
|
return response;
|
2024-01-15 15:26:13 +00:00
|
|
|
}
|
2024-12-05 02:33:46 +05:30
|
|
|
|
|
|
|
|
return null;
|
2024-01-15 15:26:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void dispose() {
|
|
|
|
|
_lastActionTime = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Creates a [Throttler] that will be disposed automatically. If no [interval] is provided, a
|
|
|
|
|
/// default interval of 300ms is used to throttle the function calls
|
2025-07-29 00:34:03 +05:30
|
|
|
Throttler useThrottler({Duration interval = const Duration(milliseconds: 300), List<Object?>? keys}) =>
|
2024-01-15 15:26:13 +00:00
|
|
|
use(_ThrottleHook(interval: interval, keys: keys));
|
|
|
|
|
|
|
|
|
|
class _ThrottleHook extends Hook<Throttler> {
|
2025-07-29 00:34:03 +05:30
|
|
|
const _ThrottleHook({required this.interval, super.keys});
|
2024-01-15 15:26:13 +00:00
|
|
|
|
|
|
|
|
final Duration interval;
|
|
|
|
|
|
|
|
|
|
@override
|
|
|
|
|
HookState<Throttler, Hook<Throttler>> createState() => _ThrottlerHookState();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class _ThrottlerHookState extends HookState<Throttler, _ThrottleHook> {
|
|
|
|
|
late final throttler = Throttler(interval: hook.interval);
|
|
|
|
|
|
|
|
|
|
@override
|
|
|
|
|
Throttler build(_) => throttler;
|
|
|
|
|
|
|
|
|
|
@override
|
|
|
|
|
void dispose() => throttler.dispose();
|
|
|
|
|
|
|
|
|
|
@override
|
|
|
|
|
String get debugLabel => 'useThrottler';
|
|
|
|
|
}
|