With Gunter's comment I made this:
import 'dart:async';
import 'dart:io';
import 'dart:isolate';
Stopwatch stopwatch = new Stopwatch();
main(args) async {
ReceivePort rPort = new ReceivePort();
rPort.listen((data) {
print("<root> $data received");
if (data is List) {
String action = data[0];
if (action == "register") {
(data[1] as SendPort).send(stopwatch.elapsedMilliseconds);
}
}
});
stopwatch.start();
await Isolate.spawn(elIsolate, rPort.sendPort);
print("isolate spawned in ${stopwatch.elapsedMilliseconds} msecs"); //isolate spawned in 377 msecs
}
void elIsolate(SendPort sPort) {
ReceivePort rPort = new ReceivePort();
rPort.listen((data) {
print("<Isolate> '$data' received"); //<Isolate> '387' received
});
sPort.send(["register", rPort.sendPort]);
}
While with Kevin's answer the code simplified to:
import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'package:stream_channel/stream_channel.dart';
Stopwatch stopwatch = new Stopwatch();
main(args) async {
ReceivePort rPort = new ReceivePort();
IsolateChannel channel = new IsolateChannel.connectReceive(rPort);
channel.stream.listen((data) {
print("<root> '$data' received at ${stopwatch.elapsedMilliseconds} msecs"); //<root> 'hello world' received at 1141 msecs
channel.sink.add(stopwatch.elapsedMilliseconds);
});
stopwatch.start();
await Isolate.spawn(elIsolate, rPort.sendPort);
print("isolate spawned in ${stopwatch.elapsedMilliseconds} msecs"); //isolate spawned in 1111 msecs
}
void elIsolate(SendPort sPort) {
IsolateChannel channel = new IsolateChannel.connectSend(sPort);
channel.stream.listen((data) {
print("<Isolate> '$data' received");
});
channel.sink.add("hello world");
}