The difference between async and async* in dart (async와 async*의 차이점)
밑의 두 자료를 참고하여 나름대로 정리해보았다.
https://dart.dev/tutorials/language/streams
Asynchronous programming: Streams
Learn how to consume single-subscriber and broadcast streams.
dart.dev
https://stackoverflow.com/questions/55397023/whats-the-difference-between-async-and-async-in-dart
What's the difference between async and async* in Dart?
I am making an application using flutter framework . During this I came across with the keywords in Dart async and async*. Can anybody tell me what's the difference between them?
stackoverflow.com
async
: You add the async keyword to a function that does some work that might take a long time. It returns the result wrapped in a Future.
Future<int> doSomeLongTask() async {
await Future.delayed(const Duration(seconds: 1));
return 42;
}
async*
: You add the async* keyword to make a function that returns a bunch of future values one at a time. The results are wrapped in a Stream.
Stream<int> countForOneMinute() async* {
for (int i = 1; i <= 60; i++) {
await Future.delayed(const Duration(seconds: 1));
yield i;
}
}
You use yield to return a value instead of return because you aren't leaving the function.
You can use await for to wait for each value emitted by the Stream.
main() async {
await for (int i in countForOneMinute()) {
print(i); // prints 1 to 60, one integer per second
}
}
아래의 코드는 Dart 공식 홈페이지에서의 예제이다.
Future<int> sumStream(Stream<int> stream) async {
var sum =0;
await for (var value in stream) {
sum +=value;
}
return sum;
}
Stream<int> countStream(int to) async* {
for (int i =1; i<=to; i++) {
yield i;
}
}
Future<void> main() async{
var stream = countStream(10);
var sum = await sumStream(stream);
print(sum);
}