Dart同步和异步函数生成器

498 阅读1分钟
类别关键字返回类型搭档
多元素同步sync*Iterable<T>yield、yield*
单元素异步asyncFuture<T>await
多元素异步async*Stream<T>yield、yield* 、await

多元素同步函数生成器

sync* + yield

sync*表明该函数返回一个Iterableyield后面是需要迭代的单个值,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*yieldawait

async*表明该函数要返回一个Stream,可以在async*函数内使用yieldyield*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';
}

参考资料:

blog.csdn.net/qq_30447263…

www.youtube.com/watch?v=TF-…