Created
June 23, 2020 08:41
-
-
Save npu3pak/970de258c251b55da3939ea37d57d5ca to your computer and use it in GitHub Desktop.
2-way communication for isolations in Dart.
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'; | |
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"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by https://medium.com/@lelandzach/dart-isolate-2-way-communication-89e75d973f34