async/async*

keystone·2021년 3월 21일
0

flutter

목록 보기
1/1

o async : gives you a Future
o async* : gives you a Stream.

[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 doSomeLongTask() async {
await Future.delayed(const Duration(seconds: 1));
return 42;
}
You can get that result by awaiting the Future:

main() async {
int result = await doSomeLongTask();
print(result); // prints '42' after waiting 1 second
}

[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 countForOneMinute() async* {
for (int i = 1; i <= 60; i++) {
await Future.delayed(const Duration(seconds: 1));
yield i;
}
}
The technical term for this is asynchronous generator function. 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
}
}

(https://stackoverflow.com/questions/55397023/whats-the-difference-between-async-and-async-in-dart)

profile
Hello, World!

0개의 댓글