rework debounce hook to be more friendly

This commit is contained in:
krawieck 2020-09-21 01:00:38 +02:00
parent 5177f93131
commit 40c36c99cd
2 changed files with 25 additions and 44 deletions

View File

@ -6,18 +6,16 @@ import 'package:flutter_hooks/flutter_hooks.dart';
import 'ref.dart';
class Debounce {
final bool pending;
final bool loading;
final void Function() start;
final void Function() cancel;
final void Function() reset;
final void Function() bounce;
call() {
bounce();
}
const Debounce({
@required this.pending,
@required this.loading,
@required this.start,
@required this.cancel,
@required this.reset,
@required this.bounce,
});
}
@ -25,33 +23,28 @@ class Debounce {
/// and loading is triggered after [delayDuration].
/// Everything can be reset with [.cancel()]
Debounce useDebounce(
Function(Function cancel) onDebounce, [
Future<Null> Function() onDebounce, [
Duration delayDuration = const Duration(milliseconds: 500),
]) {
final loading = useState(false);
final pending = useState(false);
final timerHandle = useRef<Timer>(null);
cancel() {
timerHandle.current?.cancel();
pending.value = false;
loading.value = false;
}
start() {
timerHandle.current = Timer(delayDuration, () {
timerHandle.current = Timer(delayDuration, () async {
loading.value = true;
onDebounce(cancel);
await onDebounce();
cancel();
});
pending.value = true;
}
return Debounce(
loading: loading.value,
pending: pending.value,
start: start,
cancel: cancel,
reset: () {
bounce: () {
cancel();
start();
});

View File

@ -15,39 +15,27 @@ class AddInstancePage extends HookWidget {
final instanceController = useTextEditingController();
useValueListenable(instanceController);
final accountsStore = useAccountsStore();
final delayedLoading = useDelayedLoading(Duration(milliseconds: 1000));
final delayedLoading = useDelayedLoading(Duration(milliseconds: 500));
final isSite = useState<bool>(null);
final input = useState('');
final loading = useState(false);
final icon = useState<String>(null);
final debounce = useDebounce((cancel) async {
if (instanceController.text.isNotEmpty) {
try {
icon.value =
(await LemmyApi(instanceController.text).v1.getSite()).site.icon;
isSite.value = true;
} catch (e) {
isSite.value = false;
}
cancel();
final debounce = useDebounce(() async {
if (instanceController.text.isEmpty) {
isSite.value = null;
return;
}
try {
icon.value =
(await LemmyApi(instanceController.text).v1.getSite()).site.icon;
isSite.value = true;
} catch (e) {
isSite.value = false;
}
});
onType() {
if (input.value != instanceController.text) {
isSite.value = null;
input.value = instanceController.text;
if (instanceController.text.isEmpty) {
debounce.reset();
debounce.cancel();
} else {
debounce.reset();
}
}
}
instanceController.addListener(onType);
instanceController.addListener(debounce);
handleOnAdd() async {
delayedLoading.start();