Last active
February 2, 2020 21:01
-
-
Save aryehof/894388a5cabca9a1a4ffafa203743502 to your computer and use it in GitHub Desktop.
stream/generator example
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
import 'dart:async'; | |
// Consume a stream. | |
Future<int> sumStream(Stream<int> stream) async { | |
var sum = 0; | |
await for (var value in stream) { | |
sum += value; | |
} | |
return sum; | |
} | |
// Create a stream. | |
Stream<int> countStream(int to) async* { | |
for (int i = 1; i <= to; i++) { | |
// add delay to generation of each value | |
// await Future.delayed(Duration(milliseconds: 500)); | |
yield i; | |
} | |
} | |
main() async { | |
var stream = countStream(10); | |
var sum = await sumStream(stream); | |
print(sum); // 55 | |
} |
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
// from https://dart.dev/tutorials/language/streams |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment