Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android flutter Dio锁

Android flutter Dio锁的巧妙实现方法示例

作者:linversion

这篇文章主要为大家介绍了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 (!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锁的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文