Created
August 6, 2019 02:13
-
-
Save lmzach09/147236158999f2e5a5a75e469f9cba3c to your computer and use it in GitHub Desktop.
Dart/Flutter Isolate example that has two-way message passing ability.
This file contains 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
// Example of bi-directional communication between a main thread and isolate. | |
import 'dart:io'; // for exit(); | |
import 'dart:async'; | |
import 'dart:isolate'; | |
Future<SendPort> initIsolate() async { | |
Completer completer = new Completer<SendPort>(); | |
ReceivePort isolateToMainStream = ReceivePort(); | |
isolateToMainStream.listen((data) { | |
if (data is SendPort) { | |
SendPort mainToIsolateStream = data; | |
completer.complete(mainToIsolateStream); | |
} else { | |
print('[isolateToMainStream] $data'); | |
} | |
}); | |
Isolate myIsolateInstance = await Isolate.spawn(myIsolate, isolateToMainStream.sendPort); | |
return completer.future; | |
} | |
void myIsolate(SendPort isolateToMainStream) { | |
ReceivePort mainToIsolateStream = ReceivePort(); | |
isolateToMainStream.send(mainToIsolateStream.sendPort); | |
mainToIsolateStream.listen((data) { | |
print('[mainToIsolateStream] $data'); | |
exit(0); | |
}); | |
isolateToMainStream.send('This is from myIsolate()'); | |
} | |
void main() async { | |
SendPort mainToIsolateStream = await initIsolate(); | |
mainToIsolateStream.send('This is from main()'); | |
} |
Hi - due the many langugae changes this code will not work for Dart 2.12.x
Corrected Version
import 'dart:io'; // for exit();
import 'dart:async';
import 'dart:isolate';
Future<dynamic> initIsolate() async {
Completer completer = Completer<SendPort>();
var isolateToMainStream = ReceivePort();
isolateToMainStream.listen((data) {
if (data is SendPort) {
var mainToIsolateStream = data;
completer.complete(mainToIsolateStream);
} else {
print('[isolateToMainStream] $data');
}
});
await Isolate.spawn(myIsolate, isolateToMainStream.sendPort);
return completer.future;
}
void myIsolate(SendPort isolateToMainStream) {
var mainToIsolateStream = ReceivePort();
isolateToMainStream.send(mainToIsolateStream.sendPort);
mainToIsolateStream.listen((data) {
print('[mainToIsolateStream] $data');
exit(0);
});
isolateToMainStream.send('This is from myIsolate()');
}
void main() async {
var mainToIsolateStream = await initIsolate();
mainToIsolateStream.send('This is from main()');
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output