Skip to content

Commit

Permalink
refactor(hook): refactor useDebounce
Browse files Browse the repository at this point in the history
  • Loading branch information
han2-n committed Dec 26, 2023
1 parent ebca803 commit 2a9b76d
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 13 deletions.
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
## NEXT_VERSION

### Refactor

- refactor useDebounce

## 0.0.2

- Add erb widgets
- Add erb theme

## 1.0.0

- init erb_flutter_boilerplate
40 changes: 27 additions & 13 deletions lib/core/presentation/hook/use_debounce.dart
Original file line number Diff line number Diff line change
@@ -1,19 +1,33 @@
import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

import 'use_timeout_fn.dart';
/// Signature of function that is returned by [useDebounce].
typedef DebouncedCallback = void Function(VoidCallback callback);

/// Returns a function whose invocation will be delayed by [duration].
///
/// When the returned function is called again, the previous (scheduled)
/// invocation is canceled.
///
/// See also:
///
/// * <https://rxmarbles.com/#debounce>, which this hook implements.
DebouncedCallback useDebounce(Duration duration) {
final debouncer = useMemoized(() => _Debouncer(duration), [duration]);
return debouncer.run;
}

class _Debouncer {
_Debouncer(this.duration);

final Duration duration;

// #Example
// useDebounce(() {
// bounceValue.value = inputValue.value;
// }, const Duration(seconds: 1));
Timer? _timer;

/// Flutter hook that delays invoking a function until after wait milliseconds
/// have elapsed since the last time the debounced function was invoked.
/// The third argument is the array of values that the debounce depends on,
/// in the same manner as useEffect. The debounce timeout will start when one
/// of the values changes.
void useDebounce(VoidCallback fn, Duration delay, [List<Object?>? keys]) {
final timeout = useTimeoutFn(fn, delay);
useEffect(() => timeout.reset, keys);
void run(VoidCallback callback) {
_timer?.cancel();
_timer = Timer(duration, callback);
}
}

0 comments on commit 2a9b76d

Please sign in to comment.