Android flutter Dio锁的巧妙实现方法示例
正文
看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 (!lockeandroidd) { _completer = Completer(); _lock = _completer.future; } } /// Unlock the interceptor. please开发者_JAV培训 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 interceptoandroidr is locked, the incoming request/response task /// will enter a queue. /// /// [callback] the function will rhttp://www.devze.cometurn 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锁的资料请关注我们其它相关文章!
精彩评论