Created
February 1, 2021 22:10
-
-
Save unacorbatanegra/14a4b56e611faf6e90fd66fdb5379281 to your computer and use it in GitHub Desktop.
Bidirectional communication Isolates
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 { | |
await IsolateService.init(); | |
IsolateService?.updates?.listen((e) => print('message from the isolate: $e')); | |
IsolateService.sendMessage('message from main'); | |
} | |
class IsolateService { | |
static ReceivePort _isolateToMain; | |
static StreamController<Object> _controller; | |
static SendPort _sendPort; | |
static Future<void> init() async { | |
_sendPort = await run(); | |
return; | |
} | |
static Future<SendPort> run() async { | |
_isolateToMain ??= ReceivePort(); | |
final completer = Completer<SendPort>(); | |
_controller = StreamController<Object>(); | |
_isolateToMain.listen( | |
(m) { | |
if (m is SendPort) { | |
completer.complete(m); | |
} else { | |
_controller.add(m); | |
} | |
}, | |
); | |
await Isolate.spawn(_runner, _isolateToMain.sendPort); | |
return completer.future; | |
} | |
static void sendMessage(Object message) => _sendPort?.send(message); | |
static Stream<Object> get updates => _controller?.stream; | |
static void _runner(SendPort isolateToMain) { | |
final mainToIsolate = ReceivePort(); | |
isolateToMain.send(mainToIsolate.sendPort); | |
mainToIsolate.listen((message) => print('[mainToIsolateStream] $message')); | |
isolateToMain.send('This is from my isolate'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment