What difference between await for(var msg in receivePort) and receivePort.listen()?

不羁岁月 提交于 2020-01-25 12:47:08

问题


I am learning Dart:

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");
}

I can't understand when it's better to use await for(var msg in receivePort) and when receivePort.listen()? By the first look it's doing same. Or not?


回答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");
}


来源:https://stackoverflow.com/questions/57004522/what-difference-between-await-forvar-msg-in-receiveport-and-receiveport-listen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!