When working with Streams in Dart, we need to decide actions in advance.
In order call a function every time a stream emits an event, we can use Dart’s StreamSubscription object. This object provides a listener for events and holds the callbacks used to handle them. It can also be used to unsubscribe from events or to temporarily pause the stream’s events.
To listen on a Stream, we can use the Stream.listen
method. This method returns a StreamSubscription
object.
The template for the listen
method is:
StreamSubscription<T> listen(void Function(T event) onData,
{Function onError, void Function() onDone, bool cancelOnError});
The only required parameter for the method above is the function that’s called when the data arrives. The following example shows how listen()
can be put to use:
StreamSubscription<int> subscription = stream.listen((data) { //this block is executed when data event is recieved by listenerprint('Data: $data');},onError: (err) { //this block is executed when error event is recieved by listenerprint('Error: ${err}');},cancelOnError: false, //this decides if subscription is cancelled on error or notonDone: () { //this block is executed when done event is recieved by listenerprint('Done!');},);
Now that we know how to create a StreamSubscription
object using the listen
method, we can look into some useful methods the object has:
pause([Future<void>? resumeSignal]) → void
: pauses events on a stream until further notice. The isPaused
property can be used to check if a StreamSubscription
is paused.resume() → void
: used to resume a paused stream subscription.cancel() → Future<void>
: cancels a subscription altogether. The stream subscription will not receive any events added to a stream after it is canceled.To learn more about the
StreamSubscription
class, visit Dart’s official documentation here.