Streams in Dart

Streams in Dart#

About#

In Dart, a Stream is a sequence of asynchronous events. While a Future represents a single value that will be available in the future, a Stream is designed for handling a series of values or events over time. Streams are particularly useful for scenarios where data arrives incrementally, such as handling user input, receiving data from a web socket, or processing a file line by line.

How It Works#

  • Creating a Stream: A Stream can be created in various ways, such as from a collection, through asynchronous generators using async*, or by converting a Future to a stream. Streams can be single-subscription or broadcast, determining how listeners interact with the stream.

  • Listening to a Stream: To receive data from a Stream, you listen to it using the listen method. This method takes a callback function that gets called every time the stream produces a new event. You can also handle errors and completion events with additional callbacks.

  • Pausing and Resuming: A subscription to a Stream can be paused and resumed, giving you control over when events should be processed. This is useful when dealing with streams that produce data faster than it can be processed.

Example#

void main() async {
  // Creating a stream that emits values from 1 to 5.
  Stream<int> stream = Stream.fromIterable([1, 2, 3, 4, 5]);

  // Listening to the stream and printing each value.
  await for (var value in stream) {
    print('Received: $value');
  }

  print('Stream closed');
}

Overall#

Streams in Dart are powerful tools for managing asynchronous sequences of data. They allow you to efficiently process events or data that are produced over time, ensuring that your application remains responsive even when handling large or continuous streams of information. Whether you’re dealing with user interactions, data streams, or real-time updates, Dart’s Stream API provides the flexibility and control needed to handle asynchronous events effectively.