lemmur-app-android/lib/hooks/debounce.dart

49 lines
980 B
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();
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(milliseconds: 500),
]) {
final loading = useState(false);
final timerHandle = useRef<Timer>(null);
cancel() {
timerHandle.current?.cancel();
loading.value = false;
}
start() {
timerHandle.current = Timer(delayDuration, () async {
loading.value = true;
await callback();
cancel();
});
}
return Debounce(
loading: loading.value,
callback: () {
cancel();
start();
});
}