Dart
asyncExpand
Learn stream chaining with asyncExpand.
asyncExpand
asyncExpand turns each Stream event into a new Stream and merges the results into one flow. This is also known as flat map. Each event can produce multiple sub-events.
Example: stream.asyncExpand((n) => Stream.fromIterable([n, n * 10])). Here each number produces two events: itself and ten times it. Input [1, 2, 3] gives output [1, 10, 2, 20, 3, 30].
asyncExpand turns each event into a Stream; these Streams are concatenated in order. It is used to produce multiple results from each event.
Flat map logic
asyncExpand is the Stream counterpart of the flat map operation in functional programming. Each event is turned into a Stream; these Streams are concatenated in order.
Example: stream [1, 2, 3] and transform (n) => Stream.fromIterable([n, n * 10]). 1 → [1, 10], 2 → [2, 20], 3 → [3, 30]. Merged: [1, 10, 2, 20, 3, 30].
This structure is used to derive multiple results from one event. For example gathering all orders of each user into one stream.
Exercise Expand with asyncExpand
void main() async is already written. Stream.fromIterable([1, 2, 3]) is already created. Expand each event into a two-element stream with .asyncExpand((n) => Stream.fromIterable([n, n * 10])). Listen to the result with await for and print with print.
Show example solution
void main() async {
var stream = Stream.fromIterable([1, 2, 3]);
var expanded = stream.asyncExpand((n) => Stream.fromIterable([n, n * 10]));
await for (var n in expanded) {
print(n);
}
}
Test yourself
-
What does asyncExpand turn each event into?
stream.asyncExpand((n) =>
Stream.fromIterable([n, n * 10]));
- A number
- A Future
- A new Stream
- void
Show answer
A new Stream — asyncExpand turns each event into a new Stream and merges them.
-
Match the asyncExpand parts
- (n) => Stream.fromIterable(...)
- Event to Stream
- .asyncExpand(...)
- Merge call
- [1, 10, 2, 20]
- Result stream
- await for
- Listening
-
The asyncExpand call
var expanded = stream.____((n) => Stream.fromIterable([n, n * 10]));
Show answer
var expanded = stream.asyncExpand((n) => Stream.fromIterable([n, n * 10]));
Next lesson: StreamController