Skip to content

streams

links

Streams

source: https://youtu.be/Ky8RxFF4kug?t=1842

One of the simplest streams you can implement using the periodic constructor:

Stream.periodic(const Duration(seconds:1), (n) => n);

The above code creates a stream. The first argument for the periodic constructor is the time period after which a new enters into the stream. So here after every 1 second, a new value enters the stream. The second argument is the function, where n corresponds to the number is like the number assigned to the value that enters the stream (like n is 0 for the first time a value gets added to the stream, and it keeps incrementing by 1 every time a new value gets added).

void main() {
  Stream.periodic(const Duration(seconds: 1), (n) => n + 1).listen((n) {
    print("${n} seconds later I received ${n}");
  });
}
void main() {
  Stream.periodic(const Duration(seconds: 4), (n) => n + 1).listen((n) {
    print("${n * 4} seconds later I received ${n}");
  });
}

After every second a value is released. n designates the number of value that is being released.

Creating a stream

First you need to create a StreamController.

final StreamController streamController  = StreamController<int>();

By creating a stream controller you are also linking it to a stream as a StreamController will always come back with a stream (here streamController.stream).

final StreamController streamController  = StreamController<int>();

Soon after creating the StreamController instance, we think about how we can add new values to the stream. We know we can add a single value using streamController.add method.

To get the same behavior as Stream.periodic earlier, we'll create a Timer object with its periodic constructor: Timer.periodic. Using Timer.periodic and streamController.add, we can add continuosly add new values to the stream at a definite interval.

var value = 0;
Timer.periodic(const Duration(seconds: 1), (timer) {
  streamController.add(value++);
})

Now that we have written the code that puts a value in th stream, its time to create a subscription to the stream. Remember the two entities: StreamController and StreamSubscription.

streamController.stream.listen(print)
The return value of streamController.stream.listen is a StreamSubscription; the other end of the stream. So we can declare these two side by side:

final StreamController streamController = StreamController();
final StreamSubscription streamSubscription =
  streamController.stream.listen(print)

Below this is the code that adds values to the stream:

var count = 0;
Timer.periodic(Duration(seconds: 1), (timer) {
  if (count == 5) {
    timer.cancel();
    streamController.close();
    streamSubscription.cancel();
  } else {
    streamController.add(count++);
  }
});

Comments