2024-04-30 23:38:49 +08:00
|
|
|
import 'dart:async';
|
|
|
|
|
|
|
|
|
|
class Debouncer {
|
2025-02-03 23:32:00 +08:00
|
|
|
final Map<dynamic, Timer> _operations = {};
|
2024-04-30 23:38:49 +08:00
|
|
|
|
2024-12-09 01:40:39 +08:00
|
|
|
call(
|
|
|
|
|
dynamic tag,
|
|
|
|
|
Function func, {
|
|
|
|
|
List<dynamic>? args,
|
|
|
|
|
Duration duration = const Duration(milliseconds: 600),
|
|
|
|
|
}) {
|
2025-02-03 23:32:00 +08:00
|
|
|
final timer = _operations[tag];
|
2024-12-09 01:40:39 +08:00
|
|
|
if (timer != null) {
|
|
|
|
|
timer.cancel();
|
|
|
|
|
}
|
2025-02-03 23:32:00 +08:00
|
|
|
_operations[tag] = Timer(
|
2024-12-09 01:40:39 +08:00
|
|
|
duration,
|
|
|
|
|
() {
|
2025-02-03 23:32:00 +08:00
|
|
|
_operations[tag]?.cancel();
|
|
|
|
|
_operations.remove(tag);
|
2024-12-09 01:40:39 +08:00
|
|
|
Function.apply(
|
|
|
|
|
func,
|
|
|
|
|
args,
|
|
|
|
|
);
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
}
|
2024-04-30 23:38:49 +08:00
|
|
|
|
2024-12-09 01:40:39 +08:00
|
|
|
cancel(dynamic tag) {
|
2025-02-03 23:32:00 +08:00
|
|
|
_operations[tag]?.cancel();
|
2024-04-30 23:38:49 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-02-03 23:32:00 +08:00
|
|
|
class Throttler {
|
|
|
|
|
final Map<dynamic, Timer> _operations = {};
|
|
|
|
|
|
|
|
|
|
call(
|
|
|
|
|
String tag,
|
|
|
|
|
Function func, {
|
|
|
|
|
List<dynamic>? args,
|
|
|
|
|
Duration duration = const Duration(milliseconds: 600),
|
|
|
|
|
}) {
|
|
|
|
|
final timer = _operations[tag];
|
|
|
|
|
if (timer != null) {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
_operations[tag] = Timer(
|
|
|
|
|
duration,
|
|
|
|
|
() {
|
|
|
|
|
_operations[tag]?.cancel();
|
|
|
|
|
_operations.remove(tag);
|
|
|
|
|
Function.apply(
|
|
|
|
|
func,
|
|
|
|
|
args,
|
|
|
|
|
);
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
cancel(dynamic tag) {
|
|
|
|
|
_operations[tag]?.cancel();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2024-12-09 01:40:39 +08:00
|
|
|
final debouncer = Debouncer();
|
2025-02-03 23:32:00 +08:00
|
|
|
|
|
|
|
|
final throttler = Throttler();
|