event_debouncer.dart 911 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import 'dart:async';
  2. /// EventDebouncer makes sure that events aren't fired at a higher frequency
  3. /// than specified.
  4. /// To ensure that EventDebouncer will ignore events that happen in between
  5. /// and just call the latest event that happened.
  6. class EventDebouncer {
  7. final Duration _debounceDuration;
  8. Timer? _debounceTimer;
  9. Function? _latestCallback;
  10. EventDebouncer(this._debounceDuration);
  11. void _consumeLatestCallback() {
  12. if (!(_debounceTimer?.isActive ?? false)) {
  13. _debounceTimer = null;
  14. }
  15. if (_latestCallback == null) {
  16. return;
  17. }
  18. if (_debounceTimer == null) {
  19. _latestCallback!();
  20. _latestCallback = null;
  21. _debounceTimer = Timer(
  22. _debounceDuration,
  23. () {
  24. _consumeLatestCallback();
  25. },
  26. );
  27. }
  28. }
  29. void notifyEvent(Function callback) {
  30. _latestCallback = callback;
  31. _consumeLatestCallback();
  32. }
  33. }