问题
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