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

學無先后,達者為師

網站首頁 編程語言 正文

Android?flutter?Dio鎖的巧妙實現方法示例_Android

作者:linversion ? 更新時間: 2023-03-15 編程語言

正文

看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

欄目分類
最近更新