生成器

当需要延迟地生成一个值序列时,可以考虑使用生成器函数。Dart内置支持两种生成器函数:

  • 同步生成器:返回Iterable对象
  • 异步生成器:返回Stream对象

同步生成器

要实现同步生成器函数,将函数体标记为sync*,并使用yield语句传递值

Iterable<int> nextNum(int n) sync* {
  int k = 0;
  while (k < n) yield k++;
}

void main() {
  //同步生成器的两种使用方式
  var it = nextNum(5).iterator;
  while (it.moveNext()) {
    print(it.current);
  }

  for (var i in nextNum(5)) {
    print("fori:$i");
  }
}

异步生成器

要实现异步生成器函数,将函数体标记为async*,并使用yield语句传递值

Stream<int> asyncNextNum(int n) async* {
  int k = 0;
  while (k < n) yield k++;
}

void main() async{
  //异步生成器的两种使用方式
  asyncNextNum(5).listen((value) => print(value));

  await for (var i in asyncNextNum(5)) {
    print("await fori:$i");
  }
}

递归生成器

如果生成器是递归的,则使用yield*关键字

// 同步递归生成器
Iterable<int> recursive(int n) sync* {
  if (n > 0) {
    yield n;
    yield* recursive(n - 1);
  }
}

//异步递归生成器
Stream<int> asyncRecursive(int n) async* {
  if (n > 0) {
    yield n;
    yield* asyncRecursive(n - 1);
  }
}

公众号“编程之路从0到1”

20190301102949549

Copyright © Arcticfox 2020 all right reserved,powered by Gitbook文档修订于: 2024-06-09 20:22:55

results matching ""

    No results matching ""