event_loop.dart 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import 'dart:async';
  2. import 'package:flutter/foundation.dart';
  3. typedef EventCallback<Data> = Future<dynamic> Function(Data data);
  4. abstract class BaseEvent<EventType, Data> {
  5. EventType type;
  6. Data data;
  7. /// Constructor.
  8. BaseEvent(this.type, this.data);
  9. /// Consume this event.
  10. @visibleForTesting
  11. Future<dynamic> consume() async {
  12. final cb = findCallback(type);
  13. if (cb == null) {
  14. return null;
  15. } else {
  16. return cb(data);
  17. }
  18. }
  19. EventCallback<Data>? findCallback(EventType type);
  20. }
  21. abstract class BaseEventLoop<EventType, Data> {
  22. final List<BaseEvent<EventType, Data>> _evts = [];
  23. Timer? _timer;
  24. List<BaseEvent<EventType, Data>> get evts => _evts;
  25. Future<void> onReady() async {
  26. // Poll every 100ms.
  27. _timer = Timer.periodic(Duration(milliseconds: 100), _handleTimer);
  28. }
  29. /// An Event is about to be consumed.
  30. Future<void> onPreConsume(BaseEvent<EventType, Data> evt) async {}
  31. /// An Event was consumed.
  32. Future<void> onPostConsume(BaseEvent<EventType, Data> evt) async {}
  33. /// Events are all handled and cleared.
  34. Future<void> onEventsClear() async {}
  35. /// Events start to consume.
  36. Future<void> onEventsStartConsuming() async {}
  37. Future<void> _handleTimer(Timer timer) async {
  38. if (_evts.isEmpty) {
  39. return;
  40. }
  41. timer.cancel();
  42. _timer = null;
  43. // Handle the logic.
  44. await onEventsStartConsuming();
  45. while (_evts.isNotEmpty) {
  46. final evt = _evts.first;
  47. _evts.remove(evt);
  48. await onPreConsume(evt);
  49. await evt.consume();
  50. await onPostConsume(evt);
  51. }
  52. await onEventsClear();
  53. // Now events are all processed.
  54. _timer = Timer.periodic(Duration(milliseconds: 100), _handleTimer);
  55. }
  56. Future<void> close() async {
  57. _timer?.cancel();
  58. }
  59. void pushEvent(BaseEvent<EventType, Data> evt) {
  60. _evts.add(evt);
  61. }
  62. void clear() {
  63. _evts.clear();
  64. }
  65. }