目录正文正文 看Dio库源码的时候,发现其拦截器管理的逻辑处用到了一个Lock,这个Lock巧妙地利用了Completer和Future的机制来实现,记录一下。 /// Add lo
看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;
}
}
以上就是Android Flutter Dio锁的巧妙实现方法示例的详细内容,更多关于Android flutter Dio锁的资料请关注编程网其它相关文章!
--结束END--
本文标题: AndroidflutterDio锁的巧妙实现方法示例
本文链接: https://lsjlt.com/news/178020.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0