0

我正在学习飞镖:

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

  // await for(var msg in receivePort)
  // {
  //   print(msg);
  // }

  receivePort.listen((msg) { print(msg);} ); 
}

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

我不明白什么时候使用更好,什么await for(var msg in receivePort)时候使用receivePort.listen()?乍一看,它也是如此。或不?

4

1 回答 1

1

I can say it is not the same. There is difference with listen and await for. listen just registers the handler and the execution continues. And the await for hold execution till stream is closed.

If you would add a line print('Hello World') after listen/await for lines, You will see Hello world while using listen.

Hello World
message

because execution continues after that. But with await for,

There will be no hello world until stream closed.

import 'dart:isolate';

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

  // await for(var msg in receivePort)
  // {
  //   print(msg);
  // }

  receivePort.listen((msg) { print(msg);} );
  print('Hello World');

}

echo(SendPort sendPort) async
{
  ReceivePort receivePort = ReceivePort();
  sendPort.send("message");
}
于 2019-08-13T08:31:55.427 回答