Flutter 假異步的實(shí)現(xiàn)示例
就像 android 有 handle 一樣,消息隊(duì)列這東西好像還真是系統(tǒng)必備,F(xiàn)lutter 也有自己的消息隊(duì)列,只不過隊(duì)列直接封裝在了 Dart 的線程類型 Isolate 里面了,不過 Flutter 還是提供了 Futrue 這個 API 來專門來操作各種消息,以及實(shí)現(xiàn)基于消息隊(duì)列的假異步
Flutter 的“異步”機(jī)制
這里的異步是加了引號的,可見此異步非真異步,而是假異步。Flutter 的 異步 不是開新線程,而是往所屬線程的 消息隊(duì)列 中添加任務(wù),當(dāng)然大家也可以按上文那樣自己展開真異步操作
Flutter 對代碼分2類: 同步代碼和異步代碼
- 同步代碼:傳統(tǒng)一行行寫下來,一行行執(zhí)行的代碼
- 異步代碼:通過 Future API 把任務(wù)添加到 Isolate 所屬消息隊(duì)列執(zhí)行的偽異步
- 執(zhí)行順序:先運(yùn)行同步代碼,再運(yùn)行異步代碼
為啥,很明顯啊,異步代碼是往消息隊(duì)列里添加任務(wù),那肯定得等現(xiàn)在的代碼運(yùn)行完了,線程有空閑了才能開始執(zhí)行消息隊(duì)列里的任務(wù)呀~
舉個例子:
void test() {
print("AA");
Future(() => print("Futrue"));
print("BB");
}
~~~~~~~~~~~log~~~~~~~~~~~~~
I/flutter (10064): AA
I/flutter (10064): BB
I/flutter (10064): Futrue
print("Futrue")) 任務(wù)等到最后才執(zhí)行的...
Flutter 提供了往 消息隊(duì)列 添加數(shù)據(jù)的 API: Future
往 MicroTask 隊(duì)列添加任務(wù)
scheduleMicrotask((){
// ...code goes here...
});
new Future.microtask((){
// ...code goes here...
});
往 Event 隊(duì)列添加任務(wù)
new Future(() {
// ...code goes here...
});
Future 的基本使用
Future 對象是 Flutter 專門提供的,基于消息隊(duì)列實(shí)現(xiàn)異步的類,F(xiàn)uture 對象會把自身當(dāng)做一個任務(wù)添加到消息隊(duì)列中去排隊(duì)執(zhí)行
Future 對象接受的是一個函數(shù),就是要執(zhí)行的任務(wù),用 () => ... 簡寫也是可以的
void task() {
print("AA");
}
var futrue = Future(task);
創(chuàng)建 Future 任務(wù)方式:
- Future()
- Future.microtask()
- Future.sync() - 同步任務(wù)
- Future.value()
- Future.delayed() - 延遲xx時間添加任務(wù)
- Future.error() - 錯誤處理
我們來看幾個代表性的:
Future.sync() - 阻塞任務(wù),會阻塞當(dāng)前代碼,sync 的任務(wù)執(zhí)行完了,代碼才能走到下一行
void test() {
print("AA");
Future.sync(() => print("Futrue"));
print("BB");
}
~~~~~~~~~~~~log~~~~~~~~~~~~~~
I/flutter (10573): AA
I/flutter (10573): Futrue
I/flutter (10573): BB
Future.delayed() - 延遲任務(wù),指定xx時間后把任務(wù)添加到消息隊(duì)列,要是消息隊(duì)列前面有人執(zhí)行的時間太長了,那么執(zhí)行時間點(diǎn)就不能把握了,這點(diǎn)大家要知道
void test() {
print("AA");
Future.delayed(Duration(milliseconds: 500),() => print("Futrue"));
print("BB");
}
~~~~~~~~~~~~log~~~~~~~~~~~~~~
I/flutter (10573): AA
I/flutter (10573): BB
I/flutter (10573): Futrue
Future 的鏈?zhǔn)秸{(diào)用
Future 也支持鏈?zhǔn)秸{(diào)用的,在 API 使用上也是很靈活的,提供了下面的選擇給大家
.then - 在 Future 執(zhí)行完后執(zhí)行,相當(dāng)于一個 callback,而不是重新創(chuàng)建了一個 Future
Future.delayed(Duration(seconds: 1),(){
print(("AAA"));
return "AA";
}).then((value){
print(value);
});
.catchError - future 不管在任何位置發(fā)生了錯誤,都會立即執(zhí)行 catchError
Future.delayed(Duration(seconds: 1),(){
throw Exception("AAA");
}).then((value){
print(value);
}).catchError((error){
print(error);
});
.whenComplete - 不管是否發(fā)生異常,在執(zhí)行完成后,都會執(zhí)行該方法
Future.delayed(Duration(seconds: 1), () {
throw Exception("AAA");
}).then((value) {
print(value);
}).catchError((error) {
print(error);
}).whenComplete(() {
print("complete...");
});
.wait - 可以等待所有的 future 都執(zhí)行完畢再走 then 的方法
Future.wait([
// 2秒后返回結(jié)果
Future.delayed(new Duration(seconds: 2), () {
return "hello";
}),
// 4秒后返回結(jié)果
Future.delayed(new Duration(seconds: 4), () {
return " world";
})
]).then((results) {
print(results[0] + results[1]);
}).catchError((e) {
print(e);
});
大家想想啊
Futrue() .then() .then() ...
這樣的鏈?zhǔn)綄懛ú痪褪菢?biāo)準(zhǔn)的去 callback 回調(diào)地獄的方式嘛
async/await 關(guān)鍵字
async/await 這組關(guān)鍵字是系統(tǒng)提供的另一種實(shí)現(xiàn) 異步 任務(wù)的 API, async/await 底層還是用 Futrue 實(shí)現(xiàn)的,從使用上看是對 Futrue 的簡化,本質(zhì)上還是基于 消息隊(duì)列 實(shí)現(xiàn)的異步,是 假異步 ,和 Isoalte 是不一樣的
async/await 的特點(diǎn)就是: 成對出現(xiàn)
- async - 修飾方法,用 async 聲明的方法都是耗時的
- await - 調(diào)用 async 方法時使用,也可以在 async 方法內(nèi)部是適用,await 表示阻塞,下面的任務(wù)必須等 await 調(diào)用的方法執(zhí)行完之后才能執(zhí)行
比如這樣:
anysncTest() async {
print("async 休眠 start...");
sleep(Duration(seconds: 1));
print("async 休眠 end...");
}
await anysncTest();
本質(zhì)上 await 調(diào)用的方法其實(shí)是把這個方法包裝到 Futrue 中去消息隊(duì)列里執(zhí)行,只不過是: Future.sync() 阻塞式的 Future 任務(wù)
這 async 在布局中也是可以直接用的
class TestWidgetState extends State<TestWidget> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Material(
FlatButton(
onPressed: () async {
_count = countEven(1000000000);
setState(() {});
},
child: Text(
_count.toString(),
)),
);
}
async/await 是阻塞式的函數(shù)
實(shí)驗(yàn)1:
// 這是異步任務(wù)代碼
aaa() async{
print("main1...");
await anysncTest();
print("main2...");
print("main3...");
}
anysncTest() async {
print("async 休眠 start...");
sleep(Duration(seconds: 1));
print("async 休眠 end...");
}
// 點(diǎn)擊按鈕去執(zhí)行
Widget build(BuildContext context) {
return RaisedButton(
child: (Text("click!")),
onPressed: () async {
await aaa();
},
);
}
可以看到 async/await
執(zhí)行的方法的確是阻塞時的,至少在這個 async 方法里絕對是阻塞式的
實(shí)驗(yàn)2:
那么范圍擴(kuò)展一下,在 async 外面再來看看 async/await 是不是阻塞式的? 有人說 async/await 和協(xié)程一樣 ,協(xié)程的關(guān)鍵點(diǎn)在于非競爭式資源,協(xié)程的概念中,當(dāng)多個協(xié)程中有一個協(xié)程掛起之后,并不會阻塞 CPU,CPU 回去執(zhí)行其他協(xié)程方法,直到有空閑了再來執(zhí)行之前掛起后恢復(fù)的協(xié)程,雖然在協(xié)程看來我掛起了線程,但其實(shí) CPU 不會被協(xié)程掛起阻塞,這點(diǎn)就是協(xié)程的核心優(yōu)勢,大大提升多線程下的執(zhí)行效率。
從這點(diǎn)出發(fā)我們就能知道 async/await 是不是又一個協(xié)程了,看看他阻塞 CPU,我們在 await 之后看看 async 后面的代碼會不會執(zhí)行就 OK了
// 還是這組方法
aaa() async{
print("main1...");
await anysncTest();
print("main2...");
print("main3...");
}
anysncTest() async {
print("async 休眠 start...");
sleep(Duration(seconds: 1));
print("async 休眠 end...");
}
// 執(zhí)行,注意此時按鈕的點(diǎn)擊方法不是 async 的
Widget build(BuildContext context) {
return RaisedButton(
child: (Text("click!")),
onPressed: () {
print("click1...");
aaa();
print("click2...");
print("click3...");
},
);
}
I/flutter ( 5733): click1... I/flutter ( 5733): main1... I/flutter ( 5733): async 休眠 start... I/flutter ( 5733): async 休眠 end... I/flutter ( 5733): click2... I/flutter ( 5733): click3... I/flutter ( 5733): main2... I/flutter ( 5733): main3...
await 阻塞是真的阻塞 CPU 了,所以 async/await 不是協(xié)程,但是大家注意啊,在 await 結(jié)速阻塞之后執(zhí)行的是 click2 也就是 async 外部的方法,說明 await 標(biāo)記的方法返回的都是 Futrue 對象的說法是正確的,隊(duì)列只有在線程空閑時才會執(zhí)行,顯然此時線程不是空閑的,點(diǎn)擊方法還沒執(zhí)行完呢
實(shí)驗(yàn)3:
這次做對比實(shí)驗(yàn),把點(diǎn)擊事件也變成 async 的看看執(zhí)行順序
// 還是這組方法
aaa() async{
print("main1...");
await anysncTest();
print("main2...");
print("main3...");
}
anysncTest() async {
print("async 休眠 start...");
sleep(Duration(seconds: 1));
print("async 休眠 end...");
}
// 執(zhí)行
Widget build(BuildContext context) {
return RaisedButton(
child: (Text("click!")),
onPressed: () async {
print("click1...");
await aaa();
print("click2...");
print("click3...");
},
);
}
I/flutter ( 5733): click1... I/flutter ( 5733): main1... I/flutter ( 5733): async 休眠 start... I/flutter ( 5733): async 休眠 end... I/flutter ( 5733): main2... I/flutter ( 5733): main3... I/flutter ( 5733): click2... I/flutter ( 5733): click3...
這樣看的話在 async 方法內(nèi)部,是嚴(yán)格按照順序執(zhí)行的
async 方法的格式
1. async 標(biāo)記的方法返回值都是 Futrue 類型的
上文書哦說 await 調(diào)用的方法返回的都是 Futrue 對象,那么就是說在聲明 async 函數(shù)時,返回值都是 Futrue 類型的,F(xiàn)utrue 內(nèi)部包裹實(shí)際的返回值類型
Futrue<String> getData() async {
data = await http.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
}
Futrue<String> 我們可以不寫,dart 也會自動推斷出來,但是我們一定要知道是 Futrue 類型的,要不有時會報(bào)類型錯誤
我們在用的時候都是配合 await 使用的,這時候可以直接用具體類型值接返回值了
String data = await getData();
記?。?/p>
Future就是event,很多Flutter內(nèi)置的組件比如前幾篇用到的Http(http請求控件)的get函數(shù)、RefreshIndicator(下拉手勢刷新控件)的onRefresh函數(shù)都是event。每一個被await標(biāo)記的句柄也是一個event,每創(chuàng)建一個Future就會把這個Future扔進(jìn)event queue中排隊(duì)等候安檢~
Stream
Stream 和 Future 一樣都是假異步操作,區(qū)別是 Stream 可以接受多次數(shù)據(jù),我不詳細(xì)展開了,有待以后詳細(xì)研究
Stream.fromFutures([
// 1秒后返回結(jié)果
Future.delayed(new Duration(seconds: 1), () {
return "hello 1";
}),
// 拋出一個異常
Future.delayed(new Duration(seconds: 2),(){
throw AssertionError("Error");
}),
// 3秒后返回結(jié)果
Future.delayed(new Duration(seconds: 3), () {
return "hello 3";
})
]).listen((data){
print(data);
}, onError: (e){
print(e.message);
},onDone: (){
});
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android編程設(shè)計(jì)模式之備忘錄模式詳解
這篇文章主要介紹了Android編程設(shè)計(jì)模式之備忘錄模式,結(jié)合實(shí)例形式詳細(xì)分析了Android備忘錄模式的概念、原理、應(yīng)用場景、用法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2017-12-12
android 使用 IJKPlayer 播放視頻流的實(shí)現(xiàn)代碼
這篇文章主要介紹了android 使用 IJKPlayer 播放視頻流,這需要借助 IAndroidIO 這個接口,也可以用于播放本地文件,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-11-11
Android組件之BroadcastReceiver廣播接收者
這篇文章主要為大家介紹了Android組件之BroadcastReceiver廣播接收者實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
Android自定義有限制區(qū)域圖例角度自識別涂鴉工具類中篇
這篇文章主要為大家介紹了Android自定義有限制區(qū)域圖例角度自識別涂鴉工具類詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
詳解Android中使用Notification實(shí)現(xiàn)進(jìn)度通知欄(示例三)
這篇文章主要介紹了詳解Android中使用Notification實(shí)現(xiàn)進(jìn)度通知欄(示例三),具有一定的參考價值,有興趣的可以了解一下。2016-12-12
Android實(shí)現(xiàn)軟件列表的點(diǎn)擊啟動另外一個程序功能【附demo源碼下載】
這篇文章主要介紹了Android實(shí)現(xiàn)軟件列表的點(diǎn)擊啟動另外一個程序功能,涉及Android針對應(yīng)用程序的讀取、加載、啟動等操作相關(guān)技巧,需要的朋友可以參考下2016-07-07
Android Listview點(diǎn)贊問題關(guān)于圖片重復(fù)問題
最近在開發(fā)android方面的項(xiàng)目時,遇到很多問題,下面小編以listview 與 baseadapter結(jié)合使用為例,給大家分享下關(guān)于點(diǎn)贊的的時候 圖片重復(fù)問題的解決方法,一起看看吧2016-11-11
Flutter基本組件Basics?Widget學(xué)習(xí)
本文詳細(xì)講解了Flutter基本組件Basics?Widget,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12

