0

I am trying to get answer from Isolate as list. I wrote next code. The problem That it's not working. It's simply wait.

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

  var d = await receivePort.toList();
  receivePort.close();
  print(d);
}

echo(SendPort sendPort) async
{
  ReceivePort receivePort = ReceivePort();
  sendPort.send("message");
}
Dmitry Bubnenkov
  • 9,415
  • 19
  • 85
  • 145

2 Answers2

1

The receivePort is a stream. When you call toList on the stream, it waits for the stream to complete. That never happens, so the toList call stalls forever.

If you know that the other end of the communication only sends one message, then you can instead do var d = await receivePort.first;. This only waits for the first message.

In general, when doing isolate communication, the sending isolate should send a special message when they are done, because the receiving isolate has no other way to know that. That is: You want a communication protocol, so the receiver can know whether there are going to be more messages. Maybe each message is an object which contains an isLast boolean, or the last message is null, or you wrap all messages in subclasses of a Message class that defines your protocol. What to do depends on the actual use-case. The only rule is: You have to say when you are done.

lrn
  • 64,680
  • 7
  • 105
  • 121
0

You should use .listen() instead of await for, if you want to see output of the list before is stream closed. listen will register the handler and execution keeps continue.

instead of

  var d = await receivePort.toList();
  receivePort.close();
  print(d);

try

receivePort.listen((data) => {print(data)});

You can find differences with listen and await here

Gürkan Sevinc
  • 419
  • 2
  • 5