Listening to streams
- Dart course
- Intermediate
- Lesson 65/116
- 5 min
Learn to listen to streams with listen.
The listen method
The listen method subscribes to a Stream. Each time an event arrives a callback runs. It is an alternative to await for; it gives more control.
Example: stream.listen((data) => print(data));. Each event comes to the data parameter and is printed. With onDone you give code that runs when the stream ends.
listen returns a StreamSubscription. With .asFuture() you get a Future that completes when the stream ends; you wait for it with await.
Listening flow
When you subscribe to a Stream with listen events arrive one after another. Each event is passed to the onData callback. When all events are done onDone runs.
Example: Stream.fromIterable(['A', 'B', 'C']) sends three events. listen((data) => print(data), onDone: () => print('Done')) prints A, B, C first, then Done.
With .asFuture() and await main waits until the stream completes. This makes the output deterministic.
Practice Listen and finish
void main() async is already written. Stream.fromIterable(['A', 'B', 'C']) is already created. Call stream.listen: print each event with (data) => print(data), print the end with onDone: () => print('Done'). Append .asFuture() and wait with await.
Starter code
void main() async {
var stream = Stream.fromIterable(['A', 'B', 'C']);
// listen with .listen, print done with onDone, wait with asFuture
}Sample solution
void main() async {
var stream = Stream.fromIterable(['A', 'B', 'C']);
await stream.listen(
(data) => print(data),
onDone: () => print('Done'),
).asFuture();
}Expected output
A B C Done
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does onDone run?
stream.listen(
(data) => print(data),
onDone: () => print('Done'),
);- When the Stream closes Correct answer
- Only on error
- On every event
- Never
Explanation: onDone runs when the Stream completes.
2 The listen call
var stream = Stream.fromIterable(['A', 'B', 'C']);
await stream.____(
(data) => print(data),
onDone: () => print('Done'),
).asFuture();
var stream = Stream.fromIterable(['A', 'B', 'C']);
await stream.listen(
(data) => print(data),
onDone: () => print('Done'),
).asFuture();
Explanation: listen subscribes to a Stream.
3 Match the listen parts
| Term | Meaning |
|---|---|
(data) => print(data) |
Event handler |
onDone: () => ... |
Done handler |
.asFuture() |
Completion wait |
await |
Wait for completion |