[flutter dart]sync* 和 async* 、yield 和yield* 、async 和 await

類別 關鍵字 返回類型 搭檔
多元素同步 sync* Iterable<T> yield、yield*
單元素異步 async Future<T> await
多元素異步 async* Stream<T> yield、yield* 、await

一、多元素同步函數(shù)生成器

  1. sync* 和 yield
    sync*是一個dart語法關鍵字。它標注在函數(shù){ 之前,其方法必須返回一個 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語法關鍵字。它標注在函數(shù){ 之前,其方法必須返回一個 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));
}

三、多元素異步函數(shù)生成器:
1.async和yield、await
async
是一個dart語法關鍵字。它標注在函數(shù){ 之前,其方法必須返回一個 Stream<T>對象
下面fetchEmojis被async標注,所以返回的必然是Stream對象
注意被async
標注的函數(shù),可以在其內部使用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));
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容