Single Subscription Stream Operations

Single Subscription Stream Operations

In this lesson, you will learn the usage of a Stream’s methods and properties with the help of examples. We will be using the following sample stream to carry out these operations:

Sample Stream:

We will use the following Stream to demonstrate the upcoming examples of Stream operations. This function creates a Stream of numbers from 1 to the last number passed into.

//This will generate a stream and return a reference to it.
Stream<int> createNumberStream(int last) async* {
  for (int i = 1; i <= last; i++) {
    yield i; //to be able to send spaced out events
  }
}

Using the where() Method

Let’s see an example to find and print a number greater than 3 in a number stream generated using createNumberStream(5).

In this example, the where method is called on the Stream and a listen() method is chained to the stream which acts as a callback. When a number meeting the criteria is found, it is sent over to callback to take further action on it. In the where block, any number greater than 3 is printed on the console.

The fileterUsingWhere() function demonstrates the usage of the where method to filter the numbers which are greater than 3.

In the Stream of numbers from 1 through 5, two numbers, 4 and 5, are greater than 3.

Get hands-on with 1200+ tech skills courses.