streams
links
- https://dart.dev/tutorials/language/streams
- https://api.dart.dev/stable/3.3.4/dart-async/Stream-class.html
- https://api.dart.dev/stable/3.3.4/dart-io/Process-class.html
- https://medium.com/@alvaro.armijoss/reactive-programming-in-flutter-c577d8e056d2
- https://stackoverflow.com/questions/33251129/what-is-the-best-way-to-stream-stdout-from-a-process-in-dart
- https://www.youtube.com/watch?v=nQBpOIHE4eE
Streams
source: https://youtu.be/Ky8RxFF4kug?t=1842
One of the simplest streams you can implement using the periodic constructor:
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.
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
).
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.
The return value ofstreamController.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++);
}
});