Skip to content

Instantly share code, notes, and snippets.

@npu3pak
Created June 23, 2020 08:41
Show Gist options
  • Save npu3pak/970de258c251b55da3939ea37d57d5ca to your computer and use it in GitHub Desktop.
Save npu3pak/970de258c251b55da3939ea37d57d5ca to your computer and use it in GitHub Desktop.
2-way communication for isolations in Dart.
import 'dart:async';
import 'dart:isolate';
typedef IsolateEnvironmentEntryPoint(SendPort sendPort, ReceivePort receivePort);
class IsolateEnvironment {
Isolate isolate;
ReceivePort receivePort;
SendPort sendPort;
IsolateEnvironment._(this.isolate, this.receivePort, this.sendPort);
static Future<IsolateEnvironment> spawn(IsolateEnvironmentEntryPoint entryPoint) async {
var completer = Completer<IsolateEnvironment>();
var isolateReceivePort = ReceivePort();
var envReceivePort = ReceivePort();
Isolate isolate;
isolateReceivePort.listen((msg) {
if (msg is SendPort) {
completer.complete(IsolateEnvironment._(isolate, envReceivePort, msg));
} else {
envReceivePort.sendPort.send(msg);
}
});
var args = [entryPoint, isolateReceivePort.sendPort];
isolate = await Isolate.spawn(isolateEntryPoint, args);
return completer.future;
}
static void isolateEntryPoint(List args) {
IsolateEnvironmentEntryPoint entryPoint = args[0];
SendPort sendPort = args[1];
var receivePort = ReceivePort();
sendPort.send(receivePort.sendPort);
entryPoint(sendPort, receivePort);
}
}
// Example:
main() async {
var env = await IsolateEnvironment.spawn(runIsolate);
env.receivePort.listen((msg) {
print("Received in main: $msg");
});
env.sendPort.send("Message from main");
}
runIsolate(SendPort sendPort, ReceivePort receivePort) {
receivePort.listen((msg) {
print("Received in isolate: $msg");
});
sendPort.send("Message from isolate");
}
@npu3pak
Copy link
Author

npu3pak commented Jun 23, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment