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