-
-
Save venkatd/7125882a8e86d80000ea4c2da2c2a8ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
class Debouncer { | |
final Duration delay; | |
Timer _timer; | |
Debouncer({this.delay}); | |
run(Function action) { | |
_timer?.cancel(); | |
_timer = Timer(delay, action); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// to start | |
final _debouncer = Debouncer(delay: Duration(milliseconds: 250)); | |
// and later | |
onTextChange(String text) { | |
_debouncer.run(() => print(text)); | |
} |
I prefer having the delay explicitly passed in each time so the delay is obvious.
But pretty cool, didn't know about the call
function!
Another slight variation - it can also be convenient to return a function from the call
method for the purpose of allowing us to pass arguments to the callback. For example, when listening to input coming through a stream, we can just do someStream.stream.listen(Debounce(Duration(milliseconds: 350), _fnThatTakesArgs)()
with the following:
class Debounce {
final Duration delay;
Timer _timer;
Debounce(this.delay);
Function call(Function callback) {
return (args) {
_timer?.cancel();
_timer = Timer(delay, () => callback(args));
};
}
}
How will you dispose of the timer?
@SAGARSURI, you can have something like this and call its dispose function from your user class.
class Debouncer {
Debouncer({this.delay = const Duration(milliseconds: 300)});
final Duration delay;
Timer? _timer;
void call(void Function() callback) {
_timer?.cancel();
_timer = Timer(delay, callback);
}
void dispose() {
_timer?.cancel(); // You can comment-out this line if you want. I am not sure if this call brings any value.
_timer = null;
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Slight modification based on my preference.