Creating streams in Dart

Written by Lasse Nielsen April 2013 (updated October 2018)

The dart:async library contains two typesthat are important for many Dart APIs:Stream andFuture.Where a Future represents the result of a single computation,a stream is a sequence of results.You listen on a stream to get notified of the results(both data and errors)and of the stream shutting down.You can also pause while listening or stop listening to the streambefore it is complete.

But this article is not about using streams.It’s about creating your own streams.You can create streams in a few ways:

  • Transforming existing streams.
  • Creating a stream from scratch by using an async* function.
  • Creating a stream by using a StreamController.

This article shows the code for each approachand gives tips to help you implement your stream correctly.

For help on using streams, seeAsynchronous Programming: Streams.

Transforming an existing stream

The common case for creating streams is that you already have a stream,and you want to create a new stream based on the original stream’s events.For example you might have a stream of bytes thatyou want to convert to a stream of strings by UTF-8 decoding the input.The most general approach is to create a new stream thatwaits for events on the original stream and thenoutputs new events. Example:

  1. /// Splits a stream of consecutive strings into lines.
  2. ///
  3. /// The input string is provided in smaller chunks through
  4. /// the `source` stream.
  5. Stream<String> lines(Stream<String> source) async* {
  6. // Stores any partial line from the previous chunk.
  7. var partial = '';
  8. // Wait until a new chunk is available, then process it.
  9. await for (var chunk in source) {
  10. var lines = chunk.split('\n');
  11. lines[0] = partial + lines[0]; // Prepend partial line.
  12. partial = lines.removeLast(); // Remove new partial line.
  13. for (var line in lines) {
  14. yield line; // Add lines to output stream.
  15. }
  16. }
  17. // Add final partial line to output stream, if any.
  18. if (partial.isNotEmpty) yield partial;
  19. }

For many common transformations,you can use Stream-supplied transforming methodssuch as map(), where(), expand(), and take().

For example, assume you have a stream, counterStream,that emits an increasing counter every second.Here’s how it might be implemented:

  1. var counterStream =
  2. Stream<int>.periodic(Duration(seconds: 1), (x) => x).take(15);

To quickly see the events, you can use code like this:

  1. counterStream.forEach(print); // Print an integer every second, 15 times.

To transform the stream events, you can invoke a transforming methodsuch as map() on the stream before listening to it.The method returns a new stream.

  1. // Double the integer in each event.
  2. var doubleCounterStream = counterStream.map((int x) => x * 2);
  3. doubleCounterStream.forEach(print);

Instead of map(), you could use any other transforming method,such as the following:

  1. .where((int x) => x.isEven) // Retain only even integer events.
  2. .expand((var x) => [x, x]) // Duplicate each event.
  3. .take(5) // Stop after the first five events.

Often, a transforming method is all you need.However, if you need even more control over the transformation,you can specify aStreamTransformerwith Stream’s transform() method.The platform libraries provide stream transformers for many common tasks.For example, the following code uses the utf8.decoder and LineSplittertransformers provided by the dart:convert library.

  1. Stream<List<int>> content = File('someFile.txt').openRead();
  2. List<String> lines =
  3. await content.transform(utf8.decoder).transform(LineSplitter()).toList();

Creating a stream from scratch

One way to create a new stream is withan asynchronous generator (async) function.The stream is created when the function is called,and the function’s body starts running when the stream is listened to.When the function returns, the stream closes.Until the function returns, it can emit events on the stream byusing yield or yield statements.

Here’s a primitive example that emits numbers at regular intervals:

  1. Stream<int> timedCounter(Duration interval, [int maxCount]) async* {
  2. int i = 0;
  3. while (true) {
  4. await Future.delayed(interval);
  5. yield i++;
  6. if (i == maxCount) break;
  7. }
  8. }

This function returns a Stream.When that stream is listened to, the body starts running.It repeatedly delays for the requested interval and then yields the next number.If the count parameter is omitted, there is no stop condition on the loop,so the stream outputs increasingly larger numbers forever -or until the listener cancels its subscription.

When the listener cancels(by invoking cancel() on the StreamSubscriptionobject returned by the listen() method),then the next time the body reaches a yield statement,the yield instead acts as a return statement.Any enclosing finally block is executed,and the function exits.If the function attempts to yield a value before exiting,that fails and acts as a return.

When the function finally exits, the future returned bythe cancel() method completes.If the function exits with an error, the future completes with that error;otherwise, it completes with null.

Another, more useful example is a function that convertsa sequence of futures to a stream:

  1. Stream<T> streamFromFutures<T>(Iterable<Future<T>> futures) async* {
  2. for (var future in futures) {
  3. var result = await future;
  4. yield result;
  5. }
  6. }

This function asks the futures iterable for a new future,waits for that future, emits the resulting value, and then loops.If a future completes with an error, then the stream completes with that error.

It’s rare to have an async function building a stream from nothing.It needs to get its data from somewhere,and most often that somewhere is another stream.In some cases, like the sequence of futures above,the data comes from other asynchronous event sources.In many cases, however, an async function is too simplistic toeasily handle multiple data sources.That’s where the StreamController class comes in.

Using a StreamController

If the events of your stream comes from different parts of your program,and not just from a stream or futures that can traversed by an async function,then use aStreamControllerto create and populate the stream.

A StreamController gives you a new streamand a way to add events to the stream at any point, and from anywhere.The stream has all the logic necessary to handle listeners and pausing.You return the stream and keep the controller to yourself.

The following example(from stream_controller_bad.dart)shows a basic, though flawed, usage of StreamControllerto implement the timedCounter() function from the previous examples.This code creates a stream to return,and then feeds data into it based on timer events,which are neither futures nor stream events.

  1. // NOTE: This implementation is FLAWED!
  2. // It starts before it has subscribers, and it doesn't implement pause.
  3. Stream<int> timedCounter(Duration interval, [int maxCount]) {
  4. var controller = StreamController<int>();
  5. int counter = 0;
  6. void tick(Timer timer) {
  7. counter++;
  8. controller.add(counter); // Ask stream to send counter values as event.
  9. if (maxCount != null && counter >= maxCount) {
  10. timer.cancel();
  11. controller.close(); // Ask stream to shut down and tell listeners.
  12. }
  13. }
  14.  
  15. Timer.periodic(interval, tick); // BAD: Starts before it has subscribers.
  16. return controller.stream;
  17. }

As before, you can use the stream returned by timedCounter() like this:

  1. var counterStream = timedCounter(const Duration(seconds: 1), 15);
  2. counterStream.listen(print); // Print an integer every second, 15 times.

This implementation of timedCounter() hasa couple of problems:

  • It starts producing events before it has subscribers.
  • It keeps producing events even if the subscriber requests a pause.

As the next sections show,you can fix both of these problems by specifyingcallbacks such as onListen and onPausewhen creating the StreamController.

Waiting for a subscription

As a rule, streams should wait for subscribers before starting their work.An async* function does this automatically,but when using a StreamController,you are in full control and can add events even when you shouldn’t.When a stream has no subscriber,its StreamController buffers events,which can lead to a memory leakif the stream never gets a subscriber.

Try changing the code that uses the stream to the following:

  1. void listenAfterDelay() async {
  2. var counterStream = timedCounter(const Duration(seconds: 1), 15);
  3. await Future.delayed(const Duration(seconds: 5));
  4.  
  5. // After 5 seconds, add a listener.
  6. await for (int n in counterStream) {
  7. print(n); // Print an integer every second, 15 times.
  8. }
  9. }

When this code runs,nothing is printed for the first 5 seconds,although the stream is doing work.Then the listener is added,and the first 5 or so events are printed all at once,since they were buffered by the StreamController.

To be notified of subscriptions, specify anonListen argument when you create the StreamController.The onListen callback is calledwhen the stream gets its first subscriber.If you specify an onCancel callback,it’s called when the controller loses its last subscriber.In the preceding example,Timer.periodic()should move to an onListen handler,as shown in the next section.

Honoring the pause state

Avoid producing events when the listener has requested a pause.An async* function automatically pauses at a yield statementwhile the stream subscription is paused.A StreamController, on the other hand, buffers events during the pause.If the code providing the events doesn’t respect the pause,the size of the buffer can grow indefinitely.Also, if the listener stops listening soon after pausing,then the work spent creating the buffer is wasted.

To see what happens without pause support,try changing the code that uses the stream to the following:

  1. void listenWithPause() {
  2. var counterStream = timedCounter(const Duration(seconds: 1), 15);
  3. StreamSubscription<int> subscription;
  4.  
  5. subscription = counterStream.listen((int counter) {
  6. print(counter); // Print an integer every second.
  7. if (counter == 5) {
  8. // After 5 ticks, pause for five seconds, then resume.
  9. subscription.pause(Future.delayed(const Duration(seconds: 5)));
  10. }
  11. });
  12. }

When the five seconds of pause are up,the events fired during that time are all received at once.That happens because the stream’s source doesn’t honor pausesand keeps adding events to the stream.So the stream buffers the events,and it then empties its buffer when the stream becomes unpaused.

The following version of timedCounter()(from stream_controller.dart)implements pause by using theonListen, onPause, onResume, and onCancel callbackson the StreamController.

  1. Stream<int> timedCounter(Duration interval, [int maxCount]) {
  2. StreamController<int> controller;
  3. Timer timer;
  4. int counter = 0;
  5.  
  6. void tick(_) {
  7. counter++;
  8. controller.add(counter); // Ask stream to send counter values as event.
  9. if (counter == maxCount) {
  10. timer.cancel();
  11. controller.close(); // Ask stream to shut down and tell listeners.
  12. }
  13. }
  14.  
  15. void startTimer() {
  16. timer = Timer.periodic(interval, tick);
  17. }
  18.  
  19. void stopTimer() {
  20. if (timer != null) {
  21. timer.cancel();
  22. timer = null;
  23. }
  24. }
  25.  
  26. controller = StreamController<int>(
  27. onListen: startTimer,
  28. onPause: stopTimer,
  29. onResume: startTimer,
  30. onCancel: stopTimer);
  31.  
  32. return controller.stream;
  33. }

Run this code with the listenWithPause() function above.You’ll see that it stops counting while paused,and it resumes nicely afterwards.

You must use all of the listeners—onListen,onCancel, onPause, and onResume—to benotified of changes in pause state.The reason is that if thesubscription and pause states both change at the same time,only the onListen or onCancel callback is called.

Final hints

When creating a stream without using an async* function,keep these tips in mind:

  • Be careful when using a synchronous controller—for example,one created using StreamController(sync: true).When you send an event on an unpaused synchronous controller(for example, using the add(), addError(), or close() methods defined byEventSink),the event is sent immediately to all listeners on the stream.Stream listeners must never be called untilthe code that added the listener has fully returned,and using a synchronous controller at the wrong time canbreak this promise and cause good code to fail.Avoid using synchronous controllers.

  • If you use StreamController,the onListen callback is called beforethe listen call returns the StreamSubscription.Don’t let the onListen callback dependon the subscription already existing.For example, in the following code,an onListen event fires(and handler is called)before the subscription variablehas a valid value.

  1. subscription = stream.listen(handler);
  • The onListen, onPause, onResume, and onCancelcallbacks defined by StreamController arecalled by the stream when the stream’s listener state changes,but never during the firing of an eventor during the call of another state change handler.In those cases, the state change callback is delayed untilthe previous callback is complete.

  • Don’t try to implement the Stream interface yourself.It’s easy to get the interaction between events, callbacks,and adding and removing listeners subtly wrong.Always use an existing stream, possibly from a StreamController,to implement the listen call of a new stream.

  • Although it’s possible to create classes that extend Stream withmore functionality by extending the Stream class andimplementing the listen method and the extra functionality on top,that is generally not recommended becauseit introduces a new type that users have to consider.Instead you can often make a class that has a Stream (and more) —instead of one that is a Stream (and more).