Difference between await for and listen in Dart
The main difference is when there's code afterwards. listen
only register the handler and the execution continue. await for
will retain execution until the stream is closed.
Thus if you add a print('hello');
at the end of your main
you shouldn't see hello in the output with await for
(because the request stream is never closed). Try the following code on dartpad to see the differences :
import 'dart:async';
main() async {
tenInts.listen((i) => print('int $i'));
//await for (final i in tenInts) {
// print('int $i');
//}
print('hello');
}
Stream<int> get tenInts async* {
for (int i = 1; i <= 10; i++) yield i;
}
Given:
Stream<String> stream = new Stream<String>.fromIterable(['mene', 'mene', 'tekel', 'parsin']);
then:
print('BEFORE');
stream.listen((s) { print(s); });
print('AFTER');
yields:
BEFORE
AFTER
mene
mene
tekel
parsin
whereas:
print('BEFORE');
await for(String s in stream) { print(s); }
print('AFTER');
yields:
BEFORE
mene
mene
tekel
parsin
AFTER
stream.listen()
sets up code that will be put on the event queue when an event arrives, then following code is executed.
await for
suspends between events and keeps doing so until the stream is done, so code following it will not be executed until that happens.
I use `await for when I have a stream that I know will have finite events, and I need to process them before doing anything else (essentially as if I'm dealing with a list of futures).
Check https://www.dartlang.org/articles/language/beyond-async for a description of await for
.