Isolate code didn't work as expected

Issue

Expected “Hello world” from simple isolate code shown below & didn’t work.

import 'dart:async';
import 'dart:isolate';

var mainReceivePort = new ReceivePort();

main() async {
  await Isolate.spawn(hello, null);
  await for (var msg in mainReceivePort) {  
    print(msg);
    return;
  }
}

hello(_) async {
  var sendPort = mainReceivePort.sendPort;
  sendPort.send("Hello world");
}

When following changes were made to the code, it works as intended

import 'dart:async';
import 'dart:isolate';

var mainReceivePort = new ReceivePort();

main() async {
  await Isolate.spawn(hello, mainReceivePort.sendPort);
  await for (var msg in mainReceivePort) {  
    print(msg);
    return;
  }
}

hello(sendPort) async {
  sendPort.send("Hello world");
}

Looking for clues. any thoughts?

Solution

In the first example sendPort is not connected to the main isolate, it exists only in the spawned isolate.

This code is executed in both isolates

var mainReceivePort = new ReceivePort();

and each isolate gets a different mainReceivePort instance which are not connected in any way.

In the 2nd example the sendPort connected to mainReceivePort of the main isolate is passed to the spawned isolate and messages passed to it will be received by the connected mainReceivePort of the main isolate.

Answered By – Günter Zöchbauer

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *