asyncExpand
- Dart course
- Intermediate
- Lesson 67/116
- 5 min
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.
Practice 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.
Starter code
void main() async {
var stream = Stream.fromIterable([1, 2, 3]);
// expand each number into a two-element stream with .asyncExpand, print with await for
}Sample 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);
}
}Expected output
1 10 2 20 3 30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does asyncExpand turn each event into?
stream.asyncExpand((n) =>
Stream.fromIterable([n, n * 10]));- A number
- A Future
- A new Stream Correct answer
- void
Explanation: asyncExpand turns each event into a new Stream and merges them.
2 Match the asyncExpand parts
| Term | Meaning |
|---|---|
(n) => Stream.fromIterable(...) |
Event to Stream |
.asyncExpand(...) |
Merge call |
[1, 10, 2, 20] |
Result stream |
await for |
Listening |
3 The asyncExpand call
var expanded = stream.____((n) => Stream.fromIterable([n, n * 10]));
var expanded = stream.asyncExpand((n) => Stream.fromIterable([n, n * 10]));
Explanation: asyncExpand expands each event into a Stream.