美文网首页
[flutter dart]sync* 和 async* 、yi

[flutter dart]sync* 和 async* 、yi

作者: 王冥 | 来源:发表于2025-03-10 13:14 被阅读0次

类别 关键字 返回类型 搭档
多元素同步 sync* Iterable<T> yield、yield*
单元素异步 async Future<T> await
多元素异步 async* Stream<T> yield、yield* 、await

一、多元素同步函数生成器

  1. sync* 和 yield
    sync*是一个dart语法关键字。它标注在函数{ 之前,其方法必须返回一个 Iterable<T>对象
main() {
  getEmoji(10).forEach(print);
}
 
Iterable<String> getEmoji(int count) sync* {
  Runes first = Runes('\u{1f47f}');
  for (int i = 0; i < count; i++) {
    yield String.fromCharCodes(first.map((e) => e + i));
  }
}

2、sync* 和 yield*
yield又是何许人也? 记住一点yield后面的表达式是一个Iterable<T>对象

main() {
  getEmojiWithTime(10).forEach(print);
}
 
Iterable<String> getEmojiWithTime(int count) sync* {
  yield* getEmoji(count).map((e) => '$e -- ${DateTime.now().toIso8601String()}');
}
 
Iterable<String> getEmoji(int count) sync* {
  Runes first = Runes('\u{1f47f}');
  for (int i = 0; i < count; i++) {
    yield String.fromCharCodes(first.map((e) => e + i));
  }
}

二、异步处理: async和await
async是一个dart语法关键字。它标注在函数{ 之前,其方法必须返回一个 Future<T>对象
对于耗时操作,通常用Future<T>对象异步处理

main() {
  print('程序开启--${DateTime.now().toIso8601String()}');
  fetchEmoji(1).then(print);
}
 
Future<String> fetchEmoji(int count) async{
  Runes first = Runes('\u{1f47f}');
  await Future.delayed(Duration(seconds: 2));//模拟耗时
  print('加载结束--${DateTime.now().toIso8601String()}');
  return String.fromCharCodes(first.map((e) => e + count));
}

三、多元素异步函数生成器:
1.async和yield、await
async
是一个dart语法关键字。它标注在函数{ 之前,其方法必须返回一个 Stream<T>对象
下面fetchEmojis被async标注,所以返回的必然是Stream对象
注意被async
标注的函数,可以在其内部使用yield、yield*、await关键字

main() {
  fetchEmojis(10).listen(print);
}
 
Stream<String> fetchEmojis(int count) async*{
  for (int i = 0; i < count; i++) {
    yield await fetchEmoji(i);
  }
}
 
Future<String> fetchEmoji(int count) async{
  Runes first = Runes('\u{1f47f}');
  print('加载开始--${DateTime.now().toIso8601String()}');
  await Future.delayed(Duration(seconds: 2));//模拟耗时
  print('加载结束--${DateTime.now().toIso8601String()}');
  return String.fromCharCodes(first.map((e) => e + count));
}

2.async和yield、await
和上面的yield同理,async方法内使用yield*,其后对象必须是Stream<T>对象

main() {
  getEmojiWithTime(10).listen(print);
}
 
Stream<String> getEmojiWithTime(int count) async* {
  yield* fetchEmojis(count).map((e) => '$e -- ${DateTime.now().toIso8601String()}');
}
 
Stream<String> fetchEmojis(int count) async*{
  for (int i = 0; i < count; i++) {
    yield await fetchEmoji(i);
  }
}
 
Future<String> fetchEmoji(int count) async{
  Runes first = Runes('\u{1f47f}');
  await Future.delayed(Duration(seconds: 2));//模拟耗时
  return String.fromCharCodes(first.map((e) => e + count));
}

相关文章

网友评论

      本文标题:[flutter dart]sync* 和 async* 、yi

      本文链接:https://www.haomeiwen.com/subject/oidymjtx.html