asyncExpand
- Dart course
- Advanced
- Lesson 17/83
- 5 min
Learn stream chaining with asyncExpand.
asyncExpand
asyncExpand(fn) turns each element into a new stream and concatenates them in order. The next stream is not started before the previous one completes.
Unlike expand, which synchronously maps each element to an Iterable, asyncExpand maps each element to a Stream and waits asynchronously.
Usage: make an API call per element and process results in order. Example: ids.asyncExpand((id) => fetchUserStream(id)).
asyncExpand example
Stream.fromIterable([1, 2]).asyncExpand((x) => Stream.fromIterable([x, x * 10])) yields: 1, 10, 2, 20. Each inner stream is fully consumed before moving to the next element.
This is ideal for sequential async chains. For example, take page numbers from a stream and load an API page for each.
If you want parallelism, use a Future list with Future.wait; asyncExpand is sequential.
Practice Duplicate elements with asyncExpand
Make main async. Add var s = Stream.fromIterable([1, 2]);. Add await s.asyncExpand((x) => Stream.fromIterable([x, x * 10])).forEach(print);.
Starter code
void main() {
// make async; build [1,2] stream; asyncExpand each element to [x, x*10] stream; print via forEach
}Sample solution
void main() async {
var s = Stream.fromIterable([1, 2]);
await s.asyncExpand((x) => Stream.fromIterable([x, x * 10])).forEach(print);
}Expected output
1 10 2 20
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 asyncExpand call
var t = s.____((x) => Stream.fromIterable([x, x]));
var t = s.asyncExpand((x) => Stream.fromIterable([x, x]));
Explanation: asyncExpand maps each element to a stream.
2 Match the methods
| Term | Meaning |
|---|---|
asyncExpand |
Element → Stream |
expand |
Element → Iterable |
asyncMap |
Element → Future |
map |
Element → value |
3 How does asyncExpand behave?
- Concatenates inner streams in order Correct answer
- Takes only the first element
- Processes all inner streams in parallel
- Ignores errors
Explanation: asyncExpand concatenates inner streams in order.