oscillator.dart 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 restart() {
  30. stop();
  31. start();
  32. }
  33. void start() {
  34. _value = true;
  35. _shouldRun = true;
  36. // only start right away when anyone is listening.
  37. // the moment a listener gets registered the Oscillator will start
  38. if (listeners.isNotEmpty) {
  39. _startInternal();
  40. }
  41. }
  42. void _startInternal() {
  43. if (_timer != null) return;
  44. _timer = Timer.periodic(duration, _onOscillation);
  45. }
  46. void pause() {
  47. _stopInternal();
  48. }
  49. void resume() {
  50. if (_shouldRun) {
  51. _startInternal();
  52. }
  53. }
  54. void stop() {
  55. _shouldRun = false;
  56. _stopInternal();
  57. }
  58. void _stopInternal() {
  59. _timer?.cancel();
  60. _timer = null;
  61. }
  62. }