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
Here is an example where parent creates two isolates and then two isolates also talk to each other along with the parent process.
Parent Code:
import 'dart:isolate';
import 'dart:html';
import 'dart:async';
main() {
querySelector('#output').text = 'Your Dart app is running.';
int counter = 0;
// Parent - Child 1
SendPort csendPort1;
ReceivePort receivePort1 = new ReceivePort();
// Parent - Child 2
SendPort csendPort2;
ReceivePort receivePort2 = new ReceivePort();
// Child1 - Child2
SendPort csendPort11;
SendPort csendPort12;
// Child 1
receivePort1.listen((msg) {
if (csendPort1 == null) {
csendPort1 = msg;
} else if (csendPort11 == null) {
csendPort11 = msg;
} else {
print('$msg');`enter code here`
}
});
bool child1 = false;
Isolate.spawnUri(Uri.parse('child.dart'), [], receivePort1.sendPort).then((isolate) {
print('Child 1 isolate spawned');
new Timer.periodic(const Duration(milliseconds: 500), (t) {
if (csendPort11 != null && csendPort12 != null && child1 == false) {
child1 = true;
csendPort12.send(csendPort11);
} else {
csendPort1.send('Parent-Child1: ${counter++}');
}
});
});
// Child 2
receivePort2.listen((msg) {
if (csendPort2 == null) {
csendPort2 = msg;
} else if (csendPort12 == null) {
csendPort12 = msg;
} else {
print('$msg');
}
});
bool child2 = false;
Isolate.spawnUri(Uri.parse('child.dart'), [], receivePort2.sendPort).then((isolate) {
print('Child 2 isolate spawned');
new Timer.periodic(const Duration(milliseconds: 500), (t) {
if (csendPort11 != null && csendPort12 != null && child2 == false) {
child2 = true;
csendPort11.send(csendPort12);
} else {
csendPort2.send('Parent-Child2: ${counter++}');
}
});
});
}
Child Code:
import 'dart:isolate';
import 'dart:async';
int pcounter = 0;
int ccounter = 0;
SendPort csendPort;
void handleTimeout() {
csendPort.send("${ccounter++}");
}
main(List args, SendPort psendPort) {
// Parent Comm
ReceivePort creceivePort1 = new ReceivePort();
psendPort.send(creceivePort1.sendPort);
creceivePort1.listen((msg) {
psendPort.send('Child-Parent: ${pcounter++} - ${msg}');
});
// Child-Child Comm
ReceivePort creceivePort2 = new ReceivePort();
psendPort.send(creceivePort2.sendPort);
creceivePort2.listen((msg) {
if (csendPort == null) {
csendPort = msg;
csendPort.send("${ccounter++}");
} else {
print("Child-Child: $msg");
var duration = const Duration(milliseconds: 2000);
new Timer(duration, handleTimeout);
}
});
}
HTML Code:
WebIsolateTest