0

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?

Dmitry Bubnenkov
  • 6,844
  • 12
  • 54
  • 103
  • 1
    `listen` (via the returned `StreamSubscription`) allows you to cancel the subscription. With `await for`, the only way to stop is for the `Stream` to emit an event that makes the loop exit. – jamesdlin Jul 12 '19 at 14:31
  • Possible duplicate of [Difference between await for and listen in Dart](https://stackoverflow.com/questions/42611880/difference-between-await-for-and-listen-in-dart) – Gürkan Sevinc Aug 13 '19 at 08:34

1 Answers1

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");
}
Gürkan Sevinc
  • 319
  • 1
  • 4