Skip to content

Instantly share code, notes, and snippets.

@aryehof
Last active February 2, 2020 21:01
Show Gist options
  • Save aryehof/894388a5cabca9a1a4ffafa203743502 to your computer and use it in GitHub Desktop.
Save aryehof/894388a5cabca9a1a4ffafa203743502 to your computer and use it in GitHub Desktop.
stream/generator example
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
}
// 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