Last active
August 27, 2022 11:42
-
-
Save davidgomesdev/8daf640bcd789a24cea03d1b59e4bfab to your computer and use it in GitHub Desktop.
Isolate bidirectional communication example
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:isolate'; | |
void main() async { | |
final recvPort = ReceivePort(); | |
await Isolate.spawn<SendPort>((port) { | |
print('[2] received port'); | |
final recvMsg = ReceivePort(); | |
port.send(recvMsg.sendPort); | |
print('[2] sent my port'); | |
recvMsg.listen((message) { | |
print('[2] Received ${message.name}'); | |
port.send('Thanks for ${message.name}!'); | |
}); | |
}, recvPort.sendPort); | |
final recvStream = recvPort.asBroadcastStream(); | |
final sendPort = await recvStream.first; | |
print('[1] Sending Foo'); | |
sendPort.send(Animal("Foo")); | |
print('[1] Sending Bar'); | |
sendPort.send(Animal("Bar")); | |
await for (final message in recvStream) { | |
print('[1] #2 Replied: $message'); | |
} | |
} | |
class Animal { | |
final String name; | |
Animal(this.name); | |
} | |
/* | |
Results in: | |
[2] received port | |
[2] sent my port | |
[1] Sending Foo | |
[1] Sending Bar | |
[2] Received Foo | |
[2] Received Bar | |
[1] #2 Replied: Thanks for Foo! | |
[1] #2 Replied: Thanks for Bar! | |
Note: for simplicity, this will hang just because it's awaiting forever | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment