I am learning stream in dart.
The following code shows a generator method(countStream) and a method that uses the stream(sumStream), they are from sample code from dart.dev. It works, meaning that
I can see the following output at the end.
end of for
total = 15
However, when I try to create a stream using makeCounter where I use StreamController to create a stream instead of generator (async* and yield), I can see the following output.
add
add
add
add
add
I suppose that makeCounter works because I see five "add".
How to fix this problem? Or It may impossible to create a stream with StreamController with await for.
Future<int> sumStream(Stream<int> stream) async {
var sum = 0;
await for (final value in stream) {
sum += value;
}
print("end of for");
return sum;
}
Stream<int> makeCounter(int to) {
var controller = StreamController<int>();
int counter = 0;
void tick(Timer timer) {
counter++;
print("add");
controller.add(counter);
if (counter >= to) {
timer.cancel();
}
}
Timer.periodic(Duration(seconds: 1), tick);
return controller.stream;
}
Stream<int> countStream(int to) async* {
for (int i = 1; i <= to; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
void test() async {
var stream = countStream(5);
//var stream = makeCounter(5); // this does not work correctly
var sum = await sumStream(stream);
print("total = $sum");
}