Android?flutter?Dio鎖的巧妙實現(xiàn)方法示例
正文
看Dio庫源碼的時候,發(fā)現(xiàn)其攔截器管理的邏輯處用到了一個Lock,這個Lock巧妙地利用了Completer和Future的機制來實現(xiàn),記錄一下。
/// Add lock/unlock API for interceptors.
class Lock {
Future? _lock;
late Completer _completer;
/// 標識攔截器是否被上鎖
bool get locked => _lock != null;
/// Lock the interceptor.
///
///一旦請求/響應(yīng)攔截器被鎖,后續(xù)傳入的請求/響應(yīng)攔截器將被添加到隊列中,它們將不會
///繼續(xù),直到攔截器解鎖
void lock() {
if (!locked) {
_completer = Completer();
_lock = _completer.future;
}
}
/// Unlock the interceptor. please refer to [lock()]
void unlock() {
if (locked) {
//調(diào)用complete()
_completer.complete();
_lock = null;
}
}
/// Clean the interceptor queue.
void clear([String msg = 'cancelled']) {
if (locked) {
//complete[future] with an error
_completer.completeError(msg);
_lock = null;
}
}
/// If the interceptor is locked, the incoming request/response task
/// will enter a queue.
///
/// [callback] the function will return a `Future`
/// @nodoc
Future? enqueue(EnqueueCallback callback) {
if (locked) {
// we use a future as a queue
return _lock!.then((d) => callback());
}
return null;
}
}以上就是Android flutter Dio鎖的巧妙實現(xiàn)方法示例的詳細內(nèi)容,更多關(guān)于Android flutter Dio鎖的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解Android數(shù)據(jù)存儲之Android 6.0運行時權(quán)限下文件存儲的思考
本篇文章主要介紹了Android數(shù)據(jù)存儲之Android 6.0運行時權(quán)限下文件存儲的思考,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。2016-12-12
Android UI實現(xiàn)底部切換標簽fragment
這篇文章主要為大家詳細介紹了Android UI實現(xiàn)底部切換標簽的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12
Android實現(xiàn)基于ZXing快速集成二維碼掃描功能
這篇文章主要為大家詳細介紹了Android二維碼掃描ZXing快速項目集成的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
Android Socket服務(wù)端與客戶端用字符串的方式互相傳遞圖片的方法
這篇文章主要介紹了Android Socket服務(wù)端與客戶端用字符串的方式互相傳遞圖片的方法的相關(guān)資料,需要的朋友可以參考下2016-05-05
Android編程實現(xiàn)自定義輸入法功能示例【輸入密碼時防止第三方竊取】
這篇文章主要介紹了Android編程實現(xiàn)自定義輸入法功能,可實習輸入密碼時防止第三方竊取的效果,結(jié)合實例形式詳細分析了Android布局、控件及輸入法相關(guān)操作技巧,需要的朋友可以參考下2017-01-01

