Created
December 27, 2021 06:36
-
-
Save xros/4e89af28d9e01eb0b87a501cf72c38a1 to your computer and use it in GitHub Desktop.
Stream async* and Future async in Dart
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
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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output
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.