Jac*_*ips 22
yield向周围async*函数的输出流添加一个值。就像return,但不会终止函数。
参见https://dart.dev/guides/language/language-tour#generators
Stream asynchronousNaturalsTo(n) async* {
int k = 0;
while (k < n) yield k++;
}
Run Code Online (Sandbox Code Playgroud)
执行yield语句时,它将对表达式的求值结果添加到流中。它不一定挂起(尽管在当前的实现中会挂起)。
Tok*_*yet 20
The accepted answer's link is broken, here is an official link about async* sync* yield* yield.
If you have some experiences with other languages, you might stuck at these keywords. Here are some tips for getting over keywords.
async* sync* yield* yield are called generator functions. You might use these mostly in Bloc pattern.
async* is also a async, you could use Asynchronous as usual.
sync* cannot be used as sync, you will receive the error that noticed "The modifier sync must be followed by a star".
yield and yield* can only be used with generator functions (async* sync*).
And there are four combinations.
async* yield will return a Stream<dynamic>.Stream<int> runToMax(int n) async* {
int i = 0;
while (i < n) {
yield i;
i++;
await Future.delayed(Duration(seconds: 300));
}
}
Run Code Online (Sandbox Code Playgroud)
async* yield*将调用一个函数并返回Stream<dynamic>。Stream<int> countDownFrom(int n) async* {
if (n > 0) {
yield n;
yield* countDownFrom(n - 1);
}
}
Run Code Online (Sandbox Code Playgroud)
sync* yield 将返回一个Iterable<dynamic>。Iterable<int> genIterates(int max) sync* {
var i = 0;
while (i < max) {
yield i;
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
sync* yield*将调用一个函数并返回Iterable<dynamic>。Iterable<int> countDownFrom(int n) sync* {
if (n > 0) {
yield n;
yield* countDownFrom(n - 1);
}
}
Run Code Online (Sandbox Code Playgroud)
如果有任何错误,请发表评论以更正答案。
mir*_*cal 17
我认为yield*的正确答案是委托给另一个生成器而不是调用函数。Yield* 只是委托给另一个生成器,这意味着当前生成器停止,另一个生成器接管工作,直到它停止生产。在停止生成值之后,主生成器将恢复生成自己的值。
\n感谢@Andr\xc3\xa1s Szepesh\xc3\xa1zi 鼓励我发表此评论作为答案,希望它有所帮助。
\n| 归档时间: |
|
| 查看次数: |
6078 次 |
| 最近记录: |