| 类别 | 关键字 | 返回类型 | 搭档 |
|---|---|---|---|
| 多元素同步 | sync* | Iterable<T> | yield、yield* |
| 单元素异步 | async | Future<T> | await |
| 多元素异步 | async* | Stream<T> | yield、yield* 、await |
多元素同步函数生成器
sync* + yield
sync*表明该函数返回一个Iterable;yield后面是需要迭代的单个值,yield有点像return,但是没有结束功能,相反的它提供单个值,并等待调用者请求下一个值,然后它再次执行,
syncGetString(20).forEach((element) {print(element);});
Iterable<String> syncGetString(int count) sync* {
for (int i = 0; i < count; i++) {
yield i.toString() + 'A';
}
sync* + yield*
与上面不同的是,yield*后面的表达式是一个Iterable<T>对象
syncGet(20).forEach((element) {print(element);});
Iterable<String> syncGet(int count) sync* {
yield* syncGetString(count);
}
Iterable<String> syncGetString(int count) sync* {
for (int i = 0; i < count; i++) {
yield i.toString() + 'A';
}
}
多元素异步函数生成器
async*和yield、await
async*表明该函数要返回一个Stream,可以在async*函数内使用yield、yield*、awiat关键字
asyncGetString(31).listen((event) {
print(event);
});
Stream<String> asyncGetString(int count) async* {
for (int i = 0; i < count; i++) {
yield await delayedGet(i);
}
}
Future<String> delayedGet(int i) async {
await Future.delayed(Duration(seconds: 1));
return i.toString() + 'B';
}
async*和yield*、await
和上面的yield*一样
asyncGet(31).listen((event) {
print(event);
});
Stream<String> asyncGet(int count) async* {
yield* asyncGetString(count).map((event) => event + 'C');
}
Stream<String> asyncGetString(int count) async* {
for (int i = 0; i < count; i++) {
yield await delayedGet(i);
}
}
Future<String> delayedGet(int i) async {
await Future.delayed(Duration(seconds: 1));
return i.toString() + 'B';
}
参考资料: