Edited to make the question more clear.
I am trying to work with Isolates (or Web Workers) in Dart. The only ways I can find to communicate between the
WARNING: this code only works on very old versions of Dart. It does not work on Dart 1.0 or later.
As you mention to post messages to a isolate you need to have a handle on it's sendport.
#import('dart:isolate');
main() {
SendPort sendPort = spawnFunction(doWork);
sendPort.call("hey 1").then((String res) => print("result was: [$res]"));
sendPort.call("hey 2").then((String res) => print("result was: [$res]"));
}
doWork() {
port.receive((msg, reply) {
msg = "msg $msg";
reply.send(msg);
});
}
however since the Dart main thread is itself an isolate you can send data to it by using the global port function:
#import('dart:isolate');
#import('dart:io');
main() {
port.receive((data, reply) {
// in here you can access objects created in the main thread
print("handle [${data['text']}] for index ${data['index']}");
});
SendPort workPort = spawnFunction(doWork);
workPort.send("msg", port.toSendPort());
}
doWork() {
port.receive((msg, reply) {
int i = 0;
new Timer.repeating(1000, (Timer timer) {
i++;
var data = {
"text": "$msg $i",
"index": i
};
print("sending $data");
reply.send(data);
});
});
}
Note there are certain limits about what can be send back and forth between isolates and also currently isolates act differently in JS and on the VM. The current limitations are well described here.