-
Notifications
You must be signed in to change notification settings - Fork 0
/
isolate_utils.dart
61 lines (50 loc) · 1.24 KB
/
isolate_utils.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
import 'dart:isolate';
class IsolateUtils {
late Isolate _isolate;
late SendPort _sendPort;
late ReceivePort _receivePort;
SendPort get sendPort => _sendPort;
Future<void> initIsolate() async {
_receivePort = ReceivePort();
_isolate = await Isolate.spawn<SendPort>(
_entryPoint,
_receivePort.sendPort,
);
_sendPort = await _receivePort.first;
}
static void _entryPoint(SendPort mainSendPort) async {
final childReceivePort = ReceivePort();
mainSendPort.send(childReceivePort.sendPort);
await for (final _IsolateData isolateData in childReceivePort) {
final results = await isolateData.handler(isolateData.params);
isolateData.responsePort.send(results);
}
}
void sendMessage(
Function handler,
SendPort sendPort,
ReceivePort responsePort, {
dynamic params,
}) {
final isolateData = _IsolateData(
handler,
params,
responsePort.sendPort,
);
sendPort.send(isolateData);
}
void dispose() {
_receivePort.close();
_isolate.kill(priority: Isolate.immediate);
}
}
class _IsolateData {
Function handler;
dynamic params;
SendPort responsePort;
_IsolateData(
this.handler,
this.params,
this.responsePort,
);
}