網站首頁 編程語言 正文
正文
看Dio庫源碼的時候,發現其攔截器管理的邏輯處用到了一個Lock,這個Lock巧妙地利用了Completer和Future的機制來實現,記錄一下。
/// Add lock/unlock API for interceptors.
class Lock {
Future? _lock;
late Completer _completer;
/// 標識攔截器是否被上鎖
bool get locked => _lock != null;
/// Lock the interceptor.
///
///一旦請求/響應攔截器被鎖,后續傳入的請求/響應攔截器將被添加到隊列中,它們將不會
///繼續,直到攔截器解鎖
void lock() {
if (!locked) {
_completer = Completer();
_lock = _completer.future;
}
}
/// Unlock the interceptor. please refer to [lock()]
void unlock() {
if (locked) {
//調用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;
}
}
原文鏈接:https://juejin.cn/post/7055918224528900127
相關推薦
- 2022-11-14 Go語言官方依賴注入工具Wire的使用教程_Golang
- 2022-04-20 C++中的函數你真的理解了嗎_C 語言
- 2022-07-10 promise封裝ajax請求
- 2023-01-21 VmWare安裝Centos后配置Net網絡SSH鏈接問題及解決_VMware
- 2022-09-24 ASP.NET?MVC把表格導出到Excel_實用技巧
- 2022-03-31 python常用內置模塊你了解嗎_python
- 2022-05-12 Kotlin 判斷泛型類型 reified
- 2023-10-28 如何給k8s集群里的資源打標簽_云其它
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支