您好,登錄后才能下訂單哦!
之前在Retrofit源碼初探一文中我們提出了三個問題:
其中前兩個問題在前幾篇文章已經做了解答,今天我們探究下最后一個問題:
我們定義接口時,有這樣的:
@GET("hello/world") Call<News> getNews(@Query("num") String num,@Query("page")String page);
也有這樣的:
@GET("book/search") Observable<Book> getSearchBook(@Query("q") String name, @Query("tag") String tag, @Query("start") int start, @Query("count") int count);
可以看到接口的返回值是不一樣的,現在我們就來分析下,一個OkHttpCall對象是如何轉換成對應的返回值的。
核心代碼是這句:
return serviceMethod.adapt(okHttpCall);
進到adapt中去:
T adapt(Call<R> call) { return callAdapter.adapt(call); }
可以看到是調用了callAdapter.adapt方法,此處的callAdapter是一個接口類型,所以想要看它的adapt方法的具體實現就得看這個callAdapter具體怎么生成的。
經過搜索,發現它的生成方式如下:
ServiceMethod(Builder<R, T> builder) { //……………… this.callAdapter = builder.callAdapter; //……………… }
而這個構造方法是在ServiceMethod.Builder的build方法中調用的:
public ServiceMethod build() { callAdapter = createCallAdapter(); //………… return new ServiceMethod<>(this); }
所以繼續跟進createCallAdapter()中去:
private CallAdapter<T, R> createCallAdapter() { Type returnType = method.getGenericReturnType(); if (Utils.hasUnresolvableType(returnType)) { throw methodError( "Method return type must not include a type variable or wildcard: %s", returnType); } if (returnType == void.class) { throw methodError("Service methods cannot return void."); } Annotation[] annotations = method.getAnnotations(); try { //noinspection unchecked return (CallAdapter<T, R>) retrofit.callAdapter(returnType, annotations); } catch (RuntimeException e) { // Wide exception range because factories are user code. throw methodError(e, "Unable to create call adapter for %s", returnType); } }
可以看到,這里的主要作用就是獲取方法級別的注解以及返回值,然后傳入到retrofit.callAdapter中去獲取正真的CallAdapter,所以繼續跟到retrofit.callAdatper中去:
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) { return nextCallAdapter(null, returnType, annotations); }
繼續進到nextCallAdapter中:
public CallAdapter<?, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType, Annotation[] annotations) { checkNotNull(returnType, "returnType == null"); checkNotNull(annotations, "annotations == null"); int start = callAdapterFactories.indexOf(skipPast) + 1; for (int i = start, count = callAdapterFactories.size(); i < count; i++) { CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this); if (adapter != null) { return adapter; } } //省略一些不重要代碼 }
這里主要就是遍歷Retrofit的所有CallAdapter,然后找到能夠處理該返回類型以及方法注解的那個直接返回。
對于默認返回類型的處理CallAdapter,其實是在Retrofit生成時默認加上的:
public Retrofit build() { //省略部分代碼 Executor callbackExecutor = this.callbackExecutor; if (callbackExecutor == null) { callbackExecutor = platform.defaultCallbackExecutor(); } // Make a defensive copy of the adapters and add the default Call adapter. List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories); callAdapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor)); //省略部分代碼 return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories), unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly); }
這里有一點要事先說下,所有的CalllAdapter對象其實都是通過CallAdapter.Factory對象調用get()方法生成的。
所以這里利用platform.defaultCallAdapterFactory()生成了一個對應的CallAdapter.Factory對象,但生成這個對象首先生成了一個callbackExecutor,我們先看下它是怎么回事:
@Nullable Executor defaultCallbackExecutor() { return null; }
咦,為什么是返回null的?別慌,Retrofit的build中的platform根據不同的情況會是不同的子類,并不一定是Platform的實例,而是它的子類:
static class Android extends Platform { @Override public Executor defaultCallbackExecutor() { return new MainThreadExecutor(); } @Override CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) { if (callbackExecutor == null) throw new AssertionError(); return new ExecutorCallAdapterFactory(callbackExecutor); } static class MainThreadExecutor implements Executor { private final Handler handler = new Handler(Looper.getMainLooper()); @Override public void execute(Runnable r) { handler.post(r); } } }
我們重點關注Android平臺的,可以看到這里生成的callbackExecutor的execute()方法主要就是用來將操作發送到主線程執行。
ok,callbackExecutor我們弄清楚了,那么接下來我們繼續看platform.defaultCallAdapterFactory()方法生成了什么樣的CallAdapter.Factory對象:
CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) { if (callbackExecutor != null) { return new ExecutorCallAdapterFactory(callbackExecutor); } return DefaultCallAdapterFactory.INSTANCE; }
對于Android平臺來說,我們之前生成了一個對應的callbackExecutor,所以我們繼續跟進if中的語句,發現最終生成了一個ExecutorCallAdapterFactory()對象,當然,我們主要是看它的get()方法能得到什么樣的CallAdapter對象:
@Override public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != Call.class) { return null; } final Type responseType = Utils.getCallResponseType(returnType); return new CallAdapter<Object, Call<?>>() { @Override public Type responseType() { return responseType; } @Override public Call<Object> adapt(Call<Object> call) { return new ExecutorCallbackCall<>(callbackExecutor, call); } }; }
這個get()方法生成了一個匿名的CallAdapter對象,所以:
serviceMethod.adapt(okHttpCall)最終就是調用這個匿名對象的adapt方法
可以看到adapt方法最終就是將OkHttpCall對象轉換成了ExecutorCallbackCall對象。那這個對象能干什么?
static final class ExecutorCallbackCall<T> implements Call<T> { final Executor callbackExecutor; final Call<T> delegate; ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) { this.callbackExecutor = callbackExecutor; this.delegate = delegate; } @Override public void enqueue(final Callback<T> callback) { checkNotNull(callback, "callback == null"); delegate.enqueue(new Callback<T>() { @Override public void onResponse(Call<T> call, final Response<T> response) { callbackExecutor.execute(new Runnable() { @Override public void run() { if (delegate.isCanceled()) { // Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation. callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled")); } else { callback.onResponse(ExecutorCallbackCall.this, response); } } }); } @Override public void onFailure(Call<T> call, final Throwable t) { callbackExecutor.execute(new Runnable() { @Override public void run() { callback.onFailure(ExecutorCallbackCall.this, t); } }); } }); } @Override public boolean isExecuted() { return delegate.isExecuted(); } @Override public Response<T> execute() throws IOException { return delegate.execute(); } @Override public void cancel() { delegate.cancel(); } @Override public boolean isCanceled() { return delegate.isCanceled(); } @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override public Call<T> clone() { return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone()); } @Override public Request request() { return delegate.request(); } }
可以明顯看到這個方法就是對OkHttpCall對象的一個包裝,不同的是對它的enque()方法重寫了,重寫的目的很簡單,就是為了將異步結果交給MainThreadExecutor,最終轉換到主線程執行回調。
總結
上面源碼分析了很多,有點雜亂,這里我們統一總結下OkHttpCall到接口定義的返回類型(這里以Call<ResponseBody>為例,)的轉換過程:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。