No Description

throttle.dart 834B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import 'dart:async';
  2. import 'package:meta/meta.dart';
  3. typedef VoidCallback();
  4. /// When multiple calls are repeated, only the first time is valid.
  5. ///
  6. /// Like rxdart `throttle` method
  7. class Throttle {
  8. Duration duration;
  9. VoidCallback onCall;
  10. bool _isRunning = false;
  11. Timer _timer;
  12. Throttle({
  13. @required this.onCall,
  14. this.duration = const Duration(seconds: 2),
  15. });
  16. void call() {
  17. if (!_isRunning) {
  18. _startTimer();
  19. onCall?.call();
  20. }
  21. }
  22. void _startTimer() {
  23. if (_timer != null) {
  24. _stopTimer();
  25. }
  26. _isRunning = true;
  27. _timer = Timer(duration, () {
  28. _isRunning = false;
  29. _timer = null;
  30. });
  31. }
  32. void _stopTimer() {
  33. _timer?.cancel();
  34. _isRunning = false;
  35. _timer = null;
  36. }
  37. void dispose() {
  38. this.onCall = null;
  39. _stopTimer();
  40. }
  41. }