This repository has been archived by the owner on Jun 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
isolate_utils.dart
69 lines (59 loc) · 1.55 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
62
63
64
65
66
67
68
69
import 'dart:developer';
import 'dart:isolate';
import 'package:flutter/services.dart';
class IsolateUtils {
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,
);
try {
_sendPort = await _receivePort.first;
} on Exception catch (e) {
log("Error: $e");
}
}
static void _entryPoint(SendPort mainSendPort) async {
final childReceivePort = ReceivePort('port');
mainSendPort.send(childReceivePort.sendPort);
await for (final _IsolateData? isolateData in childReceivePort) {
if (isolateData != null) {
final results = isolateData.handler(isolateData.params);
isolateData.responsePort.send(results);
}
}
}
void sendMessage({
required Function handler,
required Map<String, dynamic> params,
required SendPort sendPort,
required ReceivePort responsePort,
}) {
final isolateData = _IsolateData(
handler: handler,
params: params,
responsePort: responsePort.sendPort,
);
sendPort.send(isolateData);
}
void dispose() {
_receivePort.close();
_isolate?.kill(priority: Isolate.immediate);
_isolate = null;
}
}
class _IsolateData {
Function handler;
Map<String, dynamic> params;
SendPort responsePort;
_IsolateData({
required this.handler,
required this.params,
required this.responsePort,
});
}