Dart
Listening to streams
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.
Exercise 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.
Show example solution
void main() async {
var stream = Stream.fromIterable(['A', 'B', 'C']);
await stream.listen(
(data) => print(data),
onDone: () => print('Done'),
).asFuture();
}
Test yourself
-
When does onDone run?
stream.listen(
(data) => print(data),
onDone: () => print('Done'),
);
- When the Stream closes
- Only on error
- On every event
- Never
Show answer
When the Stream closes — onDone runs when the Stream completes.
-
The listen call
var stream = Stream.fromIterable(['A', 'B', 'C']);
await stream.____(
(data) => print(data),
onDone: () => print('Done'),
).asFuture();
Show answer
var stream = Stream.fromIterable(['A', 'B', 'C']);
await stream.listen(
(data) => print(data),
onDone: () => print('Done'),
).asFuture();
-
Match the listen parts
- (data) => print(data)
- Event handler
- onDone: () => ...
- Done handler
- .asFuture()
- Completion wait
- await
- Wait for completion
Next lesson: Stream transformation