日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Android?flutter?Dio鎖的巧妙實(shí)現(xiàn)方法示例_Android

作者:linversion ? 更新時(shí)間: 2023-03-15 編程語(yǔ)言

正文

看Dio庫(kù)源碼的時(shí)候,發(fā)現(xiàn)其攔截器管理的邏輯處用到了一個(gè)Lock,這個(gè)Lock巧妙地利用了Completer和Future的機(jī)制來(lái)實(shí)現(xiàn),記錄一下。

/// Add lock/unlock API for interceptors.
class Lock {
  Future? _lock;
  late Completer _completer;
  /// 標(biāo)識(shí)攔截器是否被上鎖
  bool get locked => _lock != null;
  /// Lock the interceptor.
  ///
 ///一旦請(qǐng)求/響應(yīng)攔截器被鎖,后續(xù)傳入的請(qǐng)求/響應(yīng)攔截器將被添加到隊(duì)列中,它們將不會(huì)
///繼續(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;
  }
}

原文鏈接:https://juejin.cn/post/7055918224528900127

欄目分類
最近更新