What you are going to learn: What are Generators? How to implement a synchronous generator function? How to implement the asynchronous generator function?
Here is the latest version of this article, https://mibcoder.com
What are Generators?
Generators can create sequence of values synchronously (by this we can create Iterable) and asynchronously (by this we can create Stream).
How to implement a synchronous generator function?
There are two thing to implement sync generator:
i- Mark function with “sync*” it defines function is generator and will return Iterable.
Iterable<int> createSyncGenerator(int n) sync* {
-----------
}
ii- Use “yeild” statement to deliver value
-------------
yield k++;
-------------
Here is example:
How to implement asynchronous generator function?
There are two thing to implement async generator:
i- Mark function with “async*” it defines function is generator and will return Stream.
Stream<int> createAsyncGenerator(int n) async* {
-------------------
}
ii- Use “yeild” statement to emit value in stream
-------------
yield k++;
-------------