Android?flutter?Dio鎖的巧妙實現(xiàn)方法示例
正文
看Dio庫源碼的時候,發(fā)現(xiàn)其攔截器管理的邏輯處用到了一個Lock,這個Lock巧妙地利用了Completer和Future的機(jī)制來實現(xiàn),記錄一下。
/// Add lock/unlock API for interceptors.
class Lock {
Future? _lock;
late Completer _completer;
/// 標(biāo)識攔截器是否被上鎖
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)方法示例的詳細(xì)內(nèi)容,更多關(guān)于Android flutter Dio鎖的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android 日志系統(tǒng)Logger源代碼詳細(xì)介紹
本文主要介紹Android 日志系統(tǒng)Logger,這里整理了關(guān)于Android源碼的日志系統(tǒng)資料,有研究Android源碼的朋友可以參考下2016-08-08
詳解Android應(yīng)用中使用TabHost組件進(jìn)行布局的基本方法
這篇文章主要介紹了Android應(yīng)用中使用TabHost組件進(jìn)行布局的基本方法,不繼承TabActivity并以最基本的布局文件方式進(jìn)行布局,需要的朋友可以參考下2016-04-04
Android開發(fā)使用URLConnection進(jìn)行網(wǎng)絡(luò)編程詳解
這篇文章主要介紹了Android開發(fā)使用URLConnection進(jìn)行網(wǎng)絡(luò)編程,結(jié)合實例形式分析了Android URLConnection對象創(chuàng)建、屬性、方法及相關(guān)使用技巧,需要的朋友可以參考下2018-01-01
Android中如何取消listview的點(diǎn)擊效果
這篇文章主要介紹了 Android中取消listview的點(diǎn)擊效果的實現(xiàn)方法,通過引用transparent之后會讓點(diǎn)擊效果透明化,一起通過本文學(xué)習(xí)吧2017-01-01
Android ListView物流獲取追蹤功能實現(xiàn)
這篇文章主要介紹了Android ListView物流獲取追蹤功能實現(xiàn)的相關(guān)資料,需要的朋友可以參考下2016-03-03
Android Studio配置Kotlin開發(fā)環(huán)境詳細(xì)步驟
這篇文章主要介紹了Android Studio配置Kotlin開發(fā)環(huán)境詳細(xì)步驟的相關(guān)資料,需要的朋友可以參考下2017-05-05

