類別 關鍵字 返回類型 搭檔
多元素同步 sync* Iterable<T> yield、yield*
單元素異步 async Future<T> await
多元素異步 async* Stream<T> yield蟋定、yield* 粉臊、await
一、多元素同步函數(shù)生成器
- 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));
}