Types of Streams
In this lesson, you will learn about the types of Streams.
We'll cover the following
Types of Streams
There are two types of Streams that one can be used to carry out the asynchronous operations.
-
Single Subscription
Single subscription streams are meant to deliver events in order. These types of streams are used when the order of events received matters; like reading a file. Such types of Streams can only be listened to once. Attempting to listen to them again will throw an exception.
-
Broadcast (Multiple subscribers)
Broadcast streams are intended to deliver events to their subscribers. Once subscribed, any subscriber can2 start listening to events. A Broadcast stream can be listened to multiple times.
Note: A Single Subscription Stream can be converted into a broadcast Stream by using the asBroadcastStream()
method.
You will learn more about these two approaches in upcoming lessons.
Subscribing to a Stream
In this section, you will learn two approaches to subscribe to a stream:
-
Using the
listen()
method -
Using a Subscription’s handler
Let’s generate a stream to demonstrate both types of subscriptions. This stream will generate numbers 1 through 5 and will throw an exception when it encounters the number 5. We’ll use createNumberStreamWithException()
to generate a Stream for the examples in this lesson.
//This will generate a stream and return a reference to it.
Stream<int> createNumberStreamWithException(int last) async* {
for (int i = 1; i <= last; i++) {
if (i == 5) {
throw new Exception("Demo exception when accessing 5th number");
}
yield i; //to be able to send spaced out events
}
}
Using listen()
The example below uses the listen()
method.
In this example, createNumberStreamWithException()
is used to generate a Stream. The Stream is listened to and prints all numbers on the console. It prints errors in the onError:
block. The onDone:
block is executed when the stream is done with its events.
The subscribeUsingListen()
is executed in main()
method.
Get hands-on with 1400+ tech skills courses.