Async and Practical
Stream Transform
where and map
Streams compose with .where(pred) and .map(fn) just like lists. Each source value is tested first, matching values are transformed, and the resulting stream can be consumed with await for.
Program
Play the program to filter source values, transform the matches, and collect the result.
stream_transform.dart
bool isEven(int n) => n % 2 == 0;
int timesTen(int n) => n * 10;
Stream<int> source() => Stream.fromIterable([1, 2, 3, 4]);
Future<List<int>> scaledEvens(Stream<int> s) async {
var out = <int>[];
await for (var n in s.where(isEven).map(timesTen)) {
out.add(n);
}
return out;
}
Future<void> main() async {
var result = await scaledEvens(source());
print('evens scaled = $result');
}
Stream.fromIterable
`Stream.fromIterable([...])` emits each value in order from a finite source.
.where
`.where(isEven)` calls the predicate for each source value and lets only `2` and `4` continue.
.map
`.map(timesTen)` transforms each kept value, so `2` becomes `20` and `4` becomes `40`.
await for collect
`await for` consumes one transformed value at a time; appending into a list lets the caller see the full result.