Retrofit 拾遺

(一)是否可以自定義 HttpClient?

Retrofit 的靜態內部類 Builder 的 client(OkHttpClient client) 方法接收 OkHttpClient 參數,但其 callFactory(okhttp3.Call.Factory factory) 方法接收 okhttp3.Call.Factory 參數,那么也就可以自定義 HttpClient,只要實現 okhttp3.Call.Factory 的 Call newCall(Request request) 就行了唄。

    public Builder client(OkHttpClient client) {
      return callFactory(checkNotNull(client, "client == null"));
    }

    public Builder callFactory(okhttp3.Call.Factory factory) {
      this.callFactory = checkNotNull(factory, "factory == null");
      return this;
    }
(二)預加載

我們知道 Retrofit 通過注解來解釋我們定義的接口方法,其中用到動態代理、反射以及解析的流程勢必會耗費時間,具體可以在自己項目中輸出 log 看下 create() 方法的耗時。

通常 app 在啟動到首頁的過程會請求多個接口,配置相關、檢測升級、拉取首頁數據等等,這種情況下可能會執行一大堆 loadServiceMethod() 方法,會帶來性能、速度方面的影響。這個時候我們就可以設置 validateEagerly 為 true 進行預加載,提前把將要用到的 serviceMethod 加載到內存里。

  public <T> T create(final Class<T> service) {
    Utils.validateServiceInterface(service);
    // 判斷是否需要預加載
    if (validateEagerly) {
      eagerlyValidateMethods(service);
    }
    // 返回一個動態代理的類對象
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
        new InvocationHandler() {
          private final Platform platform = Platform.get();
          // 代理對象調用接口方法時,便會調用該 invoke() 方法
          @Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
              throws Throwable {
            // If the method is a method from Object then defer to normal invocation.
            if (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            // 此處也是通過 loadServiceMethod 方法來返回 serviceMethod
            ServiceMethod<Object, Object> serviceMethod =
                (ServiceMethod<Object, Object>) loadServiceMethod(method);
            // 封裝了 OkHttpCall 實例來請求網絡,通常對應 OkHttp
            OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
            // 處理接口方法的返回類型 
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
  }

  private void eagerlyValidateMethods(Class<?> service) {
    Platform platform = Platform.get();
    // 遍歷接口中的所有方法
    for (Method method : service.getDeclaredMethods()) {
      if (!platform.isDefaultMethod(method)) {
        loadServiceMethod(method);
      }
    }
  }

  ServiceMethod<?, ?> loadServiceMethod(Method method) {
    // 先從緩存中讀取,如果有則返回
    ServiceMethod<?, ?> result = serviceMethodCache.get(method);
    if (result != null) return result;
    // 緩存中沒有,則構建新的并放入緩存
    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
        result = new ServiceMethod.Builder<>(this, method).build();
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }

關于動態代理可以參考:代理模式及Java實現動態代理

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,973評論 19 139
  • Retrofit是squareup公司的開源力作,和同屬squareup公司開源的OkHttp,一個負責網絡調度,...
    藍灰_q閱讀 41,909評論 23 281
  • 簡介 剛接觸Retrofit的時候,就寫了一篇簡單的使用介紹:Retrofit 2.0基本使用方法,算是對Retr...
    Whyn閱讀 2,887評論 4 24
  • 安卓開發領域中,很多重要的問題都有很好的開源解決方案,例如Square公司提供網絡請求 OkHttp , Retr...
    aaron688閱讀 1,937評論 1 20
  • 這是我最近常常思考的問題,我沒有畢業就開始實習了,連續七個月的實習后,無間斷地,我轉了正,勤奮的學習新工作,完成領...
    完顏洋洋閱讀 590評論 0 0