How does the listen method let you subscribe to a Stream and react each time it emits a new value?
Short answer
Calling the listen method on a Stream registers a callback function that Dart will automatically invoke every single time that stream actually emits a brand new value, and this listen call returns a StreamSubscription object representing that specific active subscription, which…
Advertisement
AModel answer
Calling the listen method on a Stream registers a callback function that Dart will automatically invoke every single time that stream actually emits a brand new value, and this listen call returns a StreamSubscription object representing that specific active subscription, which you can later use to pause, resume, or fully cancel your subscription to that stream whenever it is no longer actually needed, such as when a widget displaying that data is being disposed of.
final subscription = countStream().listen((value) {
print('Received: $value');
});
// Later, when no longer needed
subscription.cancel();Real-world example
A chat screen listens to a stream of incoming messages, printing each new message the moment it actually arrives, and properly cancels that subscription when the user navigates away from the chat screen entirely.
Likely follow-ups
- What happens if you forget to cancel a StreamSubscription when a widget is disposed?
- How do you handle an error that occurs partway through a stream's sequence of events?
Related topics