1
0
mirror of https://github.com/krawieck/lemmur/ synced 2024-12-16 10:30:24 +01:00
lemmur-app-android/lib/hooks/debounce.dart
2020-09-24 16:26:24 +02:00

54 lines
1.0 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'ref.dart';
class Debounce {
final bool loading;
final void Function() callback;
void call() => callback();
// void dispose() {}
const Debounce({
@required this.loading,
@required this.callback,
});
}
/// will run `callback()` after debounce hook hasn't been called for the
/// specified `delayDuration`
Debounce useDebounce(
Future<Null> Function() callback, [
Duration delayDuration = const Duration(seconds: 1),
]) {
final loading = useState(false);
final timerHandle = useRef<Timer>(null);
cancel() {
timerHandle.current?.cancel();
loading.value = false;
}
useEffect(() => () => timerHandle.current?.cancel(), []);
start() {
timerHandle.current = Timer(delayDuration, () async {
loading.value = true;
await callback();
cancel();
});
}
return Debounce(
loading: loading.value,
callback: () {
cancel();
start();
},
);
}