oscillator.dart 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import 'dart:async';
  2. import 'package:xterm/util/observable.dart';
  3. class Oscillator with Observable {
  4. Oscillator(this.duration);
  5. Oscillator.ms(int ms) : duration = Duration(milliseconds: ms);
  6. final Duration duration;
  7. var _value = true;
  8. Timer? _timer;
  9. var _shouldRun = false;
  10. @override
  11. void addListener(listener) {
  12. super.addListener(listener);
  13. resume();
  14. }
  15. @override
  16. void removeListener(listener) {
  17. super.removeListener(listener);
  18. if (listeners.isEmpty) {
  19. pause();
  20. }
  21. }
  22. void _onOscillation(_) {
  23. _value = !_value;
  24. notifyListeners();
  25. }
  26. bool get value {
  27. return _value;
  28. }
  29. void start() {
  30. _shouldRun = true;
  31. // only start right away when anyone is listening.
  32. // the moment a listener gets registered the Oscillator will start
  33. if (listeners.isNotEmpty) {
  34. _startInternal();
  35. }
  36. }
  37. void _startInternal() {
  38. if (_timer != null) return;
  39. _timer = Timer.periodic(duration, _onOscillation);
  40. }
  41. void pause() {
  42. _stopInternal();
  43. }
  44. void resume() {
  45. if (_shouldRun) {
  46. _startInternal();
  47. }
  48. }
  49. void stop() {
  50. _shouldRun = false;
  51. _stopInternal();
  52. }
  53. void _stopInternal() {
  54. _timer?.cancel();
  55. _timer = null;
  56. }
  57. }