Async and Practical
Streams
Stream.fromIterable and await for
A Stream<T> delivers a sequence of values asynchronously. Stream.fromIterable(xs) builds a finite stream that emits each value in order and then completes. await for (var n in stream) consumes one value at a time inside an async function.
Program
Play the program to sum a finite stream by iterating it with await for.
stream_from_iterable.dart
Replay: real traced execution (multi-file project)
Future<int> sumStream(Stream<int> source) async {
var total = 0;
await for (var n in source) {
total += n;
}
return total;
}
Future<void> main() async {
var stream = Stream.fromIterable([1, 2, 3, 4]);
var total = await sumStream(stream);
print(total);
}
stream ← Stream.fromIterable([1, 2, 3, 4])
9Future<void> main() async {10 var stream = Stream.fromIterable([1, 2, 3, 4]);11 var total = await sumStream(stream);values this stepStream.fromIterable([1, 2, 3, 4])streamawait ← suspended
10var stream = Stream.fromIterable([1, 2, 3, 4]);11var total = await sumStream(stream);12print(total);values this stepsumStream(stream) → suspendedawaittotal ← 0
1Future<int> sumStream(Stream<int> source) async {2 var total = 0;3 await for (var n in source) {values this step0totalstream event ← emit n = 1
2var total = 0;3await for (var n in source) {4 total += n;values this stepemit n = 1stream eventtotal ← 1
3await for (var n in source) {4 total += n;5}values this step0 → 1total1nstream event ← emit n = 2
2var total = 0;3await for (var n in source) {4 total += n;values this stepemit n = 2stream eventtotal ← 3
3await for (var n in source) {4 total += n;5}values this step1 → 3total2nstream event ← emit n = 3
2var total = 0;3await for (var n in source) {4 total += n;values this stepemit n = 3stream eventtotal ← 6
3await for (var n in source) {4 total += n;5}values this step3 → 6total3nstream event ← emit n = 4
2var total = 0;3await for (var n in source) {4 total += n;values this stepemit n = 4stream eventtotal ← 10
3await for (var n in source) {4 total += n;5}values this step6 → 10total4nstream event ← done (closed)
2var total = 0;3await for (var n in source) {4 total += n;values this stepdone (closed)stream eventreturn value ← 10
5 }6 return total;7}values this step10return value10totalawait ← resolved total = 10
10var stream = Stream.fromIterable([1, 2, 3, 4]);11var total = await sumStream(stream);12print(total);values this stepresolved total = 10awaitprint(total);
11 var total = await sumStream(stream);12 print(total);13}output10values this step10total
Stream.fromIterable
`Stream.fromIterable(xs)` builds a finite stream that emits each value in order and then closes.
await for
`await for (var n in source)` pauses the surrounding async function until the next value (or completion) is available.
loop completion
When the stream signals it has no more values, the `await for` loop ends and the function continues.