debounce<T> method
void
debounce<T>(
- RxInterface<
T> rx, - void callback(
- T
- Duration duration = const Duration(milliseconds: 400),
inherited
Calls callback after rx stops changing for duration.
Useful for search-as-you-type, form validation, etc.
debounce(searchQuery, (q) => fetchResults(q),
duration: const Duration(milliseconds: 500));
Implementation
void debounce<T>(
RxInterface<T> rx,
void Function(T) callback, {
Duration duration = const Duration(milliseconds: 400),
}) {
Timer? timer;
void schedule(T val) {
if (timer != null) {
_timers.remove(timer);
timer!.cancel();
}
late Timer nextTimer;
nextTimer = Timer(duration, () {
_timers.remove(nextTimer);
if (!isDisposed) {
callback(val);
}
});
timer = nextTimer;
_timers.add(nextTimer);
}
if (rx is SintListenable<T>) {
final disposer = rx.addListener(() {
if (!isDisposed && !rx.isDisposed) {
schedule(rx.peek);
}
});
_syncDisposers.add(disposer);
return;
}
_workers.add(rx.listen(schedule));
}