Last active
December 4, 2022 09:49
-
-
Save mutant0113/eab29691c44f8e2e9dc0bd6739cf0a1f to your computer and use it in GitHub Desktop.
flutter_isolate_spawn
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'dart:isolate'; | |
void main() async { | |
// 1. Create the main receive port. | |
final mainReceivePort = ReceivePort(); | |
// 2. Spawn an isolate with the main send port. | |
final newIsolate = await Isolate.spawn(createNewIsolate, mainReceivePort.sendPort); | |
mainReceivePort.listen((message) { | |
// 5. Receive send port of the new isolate. | |
if (message is SendPort) { | |
// 6. Send value to new isolate. | |
int value = 1; | |
print("main Isolate: Message sent to new Isolate: $value"); | |
message.send(value); | |
} else { | |
// 9. Receive the result. | |
print("main Isolate: Received message from new Isolate: $message"); | |
} | |
}); | |
} | |
void createNewIsolate(SendPort mainSendPort) { | |
// 3. Create a receive port in the new Isolate. | |
final isolateReceivePort = ReceivePort(); | |
// 4. Send send port of the new isolate back to main isolate. | |
mainSendPort.send(isolateReceivePort.sendPort); | |
isolateReceivePort.listen((message) async { | |
print("new Isolate: Received message from main Isolate: $message"); | |
// 7. Receive value from main isolate. | |
if (message is int) { | |
// 8. Do the task and send the result back to main isolate. | |
final result = await heavyTask(message); | |
print("new Isolate: Message sent to main Isolate: result"); | |
mainSendPort.send(result); | |
} | |
}); | |
} | |
Future<int> heavyTask(int value) => Future.delayed(const Duration(seconds: 3), () => value + 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment