What does the * of the reserved words Sync*, async*, Yield* mean?

Asked

Viewed 155 times

1

What does the * of reserved words Sync*, async*, Yield*mean? What’s the difference between them and their similar Sync, async and Yield?

  • If I understand correctly, an async function returns a Future (a delayed task), while an async* function is a generator of several delayed tasks. Source: https://stackoverflow.com/questions/55397023/whats-the-difference-between-async-and-async-in-dart (last reply).

  • 1

    @epx Correct 'several tasks' actually are or are the Streams, which may be used with yield / yield*.

1 answer

2


These words are called "Star-Keywords" and are used in generator functions.

Explaining better

They are used in functions that will return data on-demand, that is, only when we actually make use of the data that will be returned.
This serves both synchronous functions (Sync*) and asynchronous functions (async*).

Example

Let me give you an example using a Interable<int> only for the understanding of *

void main() {
  print('create iterator');
  Iterable<int> numbers = getNumbers(3);
  print('starting to iterate...');
  for (int val in numbers) {
    print('$val');
  }
  print('end of main');
}

Iterable<int> getNumbers(int number) sync* {
  print('generator started');
  for (int i = 0; i < number; i++) {
    yield i;
  }
  print('generator ended');
}

Run this program on Dartpad and see the following result:

create iterator
starting to iterate...
generator started
0
1
2
generator ended
end of main

As can be seen in the return log, the generator only started when the variable numbers was actually used, i.e., the values returned by the method getNumbers were generated only at the time when they were needed.

Sources:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.