How to get simple answer from isolate?

Issue

I am learning about Isolate‘s. I read docs. And want to write minimal working example. Here is my code:

main() async
 {

  ReceivePort receivePort = ReceivePort();
  Isolate.spawn(echo, receivePort.sendPort);

  var sendPort = await receivePort.first;

 }


 echo(SendPort sendPort)
 {
   ReceivePort receivePort = ReceivePort();
   sendPort.send(receivePort);
 }

It almost ok, but I can’t understand how I can send simple “Hello” message back. I looked few examples and there was some middle-ware like sendReceive(). Im I right understand that after:

var sendPort = await receivePort.first;

sendPort will store name/address of spawned function and I need sendPort.send("hello");?

Solution

You already stated how to send simple data using SendPort.send. In fact, you are only able to send primitive data types, i.e. null, num, bool, double, String as described in the documentation.
I will complete your example in the following.

import 'dart:isolate';

main() async {
  final receivePort = ReceivePort();
  await Isolate.spawn(echo, receivePort.sendPort);

  final Stream receivePortStream = receivePort.asBroadcastStream();

  receivePortStream.listen((message) {
    if (message is String) {
      print('Message from listener: $message');
    } else if (message is num) {
      print('Computation result: $message');
    }
  });

  final firstMessage = await receivePortStream.first;
  print(firstMessage);
}

echo(SendPort sendPort) {
  sendPort.send('hello');

  sendPort.send('another one');

  final computationResult = 27 * 939;
  sendPort.send(computationResult);
}

Note that you want to simply send 'hello' and not some other ReceivePort, which will not even work as it is not a primitive value.
In my example, I also setup another listener that will process further messages.

Additionally, I needed to create the receivePortStream variable as a broadcast stream in order to be able to both listen to it and get the first message. If you try to run ReceivePort.listen and ReceivePort.first on the same ReceivePort, you will get an exception.

Answered By – creativecreatorormaybenot

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.