Trusted answers to developer questions

What is the StreamSubscription class in Dart?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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 listener
print('Data: $data');
},
onError: (err) { //this block is executed when error event is recieved by listener
print('Error: ${err}');
},
cancelOnError: false, //this decides if subscription is cancelled on error or not
onDone: () { //this block is executed when done event is recieved by listener
print('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.

RELATED TAGS

dart

CONTRIBUTOR

Anusheh Zohair Mustafeez
Did you find this helpful?