Created with <3 with dartpad.dev.
Last active
December 28, 2023 13:30
-
-
Save catalunha/0c9c63deb9ca93980e5fd56579d76961 to your computer and use it in GitHub Desktop.
streamTest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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