Skip to content

Instantly share code, notes, and snippets.

@xros
Created December 27, 2021 06:36
Show Gist options
  • Save xros/4e89af28d9e01eb0b87a501cf72c38a1 to your computer and use it in GitHub Desktop.
Save xros/4e89af28d9e01eb0b87a501cf72c38a1 to your computer and use it in GitHub Desktop.
Stream async* and Future async in Dart
Future<int> sumStream(Stream<int> stream) async {
int sum = 0;
await for (var i in stream) {
sum += i;
}
return sum;
}
Future<int> sumStream2(Stream<int> stream) =>
stream.reduce((previous, element) => previous + element);
// Stream generator 异步的 asynchronous
Stream<int> countStream(int n) async* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
// Iterable generator 同步的 synchronous
Iterable<int> count(int n) sync* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
Future<void> main() async {
print('----- lets see Stream and Future ----');
final stream = Stream<int>.fromIterable([1, 2, 3, 4]);
final sum = await sumStream2(stream);
print(sum);
print('-----create stream using stream operator async* -----');
final stream2 = countStream(4);
final sum2 = await sumStream(stream2);
print(sum2);
print('-----create iterable using Iterable operator sync* -----');
final myIter = count(4);
print(myIter.reduce((value, element) => value + element));
}
@xros
Copy link
Author

xros commented Dec 27, 2021

output

----- lets see Stream and Future ----
10
-----create stream using stream operator async* -----
10
-----create iterable using Iterable operator sync* -----
10

Stream with Future. stream is a iterable of future instance.

hard to understand.

stream.reduce() waits for each event to be available before calling the combined function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment