Skip to content
DeveloperMemos

Understanding async and async*/yield in Dart

Dart, Async, Programming1 min read

In Dart, the keywords async and async* are used to handle asynchronous operations, but they serve different purposes. This article explains the differences between them - with some practical examples included.

What is async?

The async keyword is used to mark a function as asynchronous. It allows the use of await within the function and returns a Future.

Example of async:

1Future<int> doSomeLongTask() async {
2 await Future.delayed(const Duration(seconds: 1));
3 return 42;
4}
5
6void main() async {
7 int result = await doSomeLongTask();
8 print(result); // prints '42' after waiting 1 second
9}

What is async*?

The async* keyword marks a function as an asynchronous generator, which returns a Stream of values instead of a single value.

Example of async*:

1Stream<int> countForOneMinute() async* {
2 for (int i = 1; i <= 60; i++) {
3 await Future.delayed(const Duration(seconds: 1));
4 yield i;
5 }
6}
7
8void main() async {
9 await for (int i in countForOneMinute()) {
10 print(i); // prints 1 to 60, one integer per second
11 }
12}

Key Differences

  • async functions return a Future and are useful for single asynchronous operations.
  • async* functions return a Stream and are used to emit multiple asynchronous values over time.
  • yield is used in async* functions to emit values, while return is used in async functions.

Best Practices

  • Use async for functions that perform a single asynchronous task and need to return a value.
  • Use async* for functions that need to emit multiple values over time, such as in data streams or periodic updates.