Skip to content

Instantly share code, notes, and snippets.

@catalunha
Last active December 28, 2023 13:30
Show Gist options
  • Save catalunha/0c9c63deb9ca93980e5fd56579d76961 to your computer and use it in GitHub Desktop.
Save catalunha/0c9c63deb9ca93980e5fd56579d76961 to your computer and use it in GitHub Desktop.
streamTest
void main() async {
/// Initialize a stream of integers 0-9
Stream<int> stream = countStream(10);
/// Compute the sum of the stream of integers
int sum = await sumStream(stream);
/// Print the sum
print(sum); // 45
}
Stream<int> countStream(int max) async* {
for (int i = 0; i < max; i++) {
print('i: $i');
await Future.delayed(Duration(seconds: 2));
yield i;
}
}
Future<int> sumStream(Stream<int> stream) async {
int sum = 0;
await for (int value in stream) {
sum += value;
print('sum: $sum');
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment