您好,登錄后才能下訂單哦!
之前在Retrofit源碼初探一文中我們提出了三個(gè)問題:
其中前兩個(gè)問題在前幾篇文章已經(jīng)做了解答,今天我們探究下最后一個(gè)問題:
我們定義接口時(shí),有這樣的:
@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);
可以看到接口的返回值是不一樣的,現(xiàn)在我們就來分析下,一個(gè)OkHttpCall對(duì)象是如何轉(zhuǎn)換成對(duì)應(yīng)的返回值的。
核心代碼是這句:
return serviceMethod.adapt(okHttpCall);
進(jìn)到adapt中去:
T adapt(Call<R> call) { return callAdapter.adapt(call); }
可以看到是調(diào)用了callAdapter.adapt方法,此處的callAdapter是一個(gè)接口類型,所以想要看它的adapt方法的具體實(shí)現(xiàn)就得看這個(gè)callAdapter具體怎么生成的。
經(jīng)過搜索,發(fā)現(xiàn)它的生成方式如下:
ServiceMethod(Builder<R, T> builder) { //……………… this.callAdapter = builder.callAdapter; //……………… }
而這個(gè)構(gòu)造方法是在ServiceMethod.Builder的build方法中調(diào)用的:
public ServiceMethod build() { callAdapter = createCallAdapter(); //………… return new ServiceMethod<>(this); }
所以繼續(xù)跟進(jìn)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); } }
可以看到,這里的主要作用就是獲取方法級(jí)別的注解以及返回值,然后傳入到retrofit.callAdapter中去獲取正真的CallAdapter,所以繼續(xù)跟到retrofit.callAdatper中去:
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) { return nextCallAdapter(null, returnType, annotations); }
繼續(xù)進(jìn)到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,然后找到能夠處理該返回類型以及方法注解的那個(gè)直接返回。
對(duì)于默認(rèn)返回類型的處理CallAdapter,其實(shí)是在Retrofit生成時(shí)默認(rèn)加上的:
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); }
這里有一點(diǎn)要事先說下,所有的CalllAdapter對(duì)象其實(shí)都是通過CallAdapter.Factory對(duì)象調(diào)用get()方法生成的。
所以這里利用platform.defaultCallAdapterFactory()生成了一個(gè)對(duì)應(yīng)的CallAdapter.Factory對(duì)象,但生成這個(gè)對(duì)象首先生成了一個(gè)callbackExecutor,我們先看下它是怎么回事:
@Nullable Executor defaultCallbackExecutor() { return null; }
咦,為什么是返回null的?別慌,Retrofit的build中的platform根據(jù)不同的情況會(huì)是不同的子類,并不一定是Platform的實(shí)例,而是它的子類:
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); } } }
我們重點(diǎn)關(guān)注Android平臺(tái)的,可以看到這里生成的callbackExecutor的execute()方法主要就是用來將操作發(fā)送到主線程執(zhí)行。
ok,callbackExecutor我們弄清楚了,那么接下來我們繼續(xù)看platform.defaultCallAdapterFactory()方法生成了什么樣的CallAdapter.Factory對(duì)象:
CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) { if (callbackExecutor != null) { return new ExecutorCallAdapterFactory(callbackExecutor); } return DefaultCallAdapterFactory.INSTANCE; }
對(duì)于Android平臺(tái)來說,我們之前生成了一個(gè)對(duì)應(yīng)的callbackExecutor,所以我們繼續(xù)跟進(jìn)if中的語句,發(fā)現(xiàn)最終生成了一個(gè)ExecutorCallAdapterFactory()對(duì)象,當(dāng)然,我們主要是看它的get()方法能得到什么樣的CallAdapter對(duì)象:
@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); } }; }
這個(gè)get()方法生成了一個(gè)匿名的CallAdapter對(duì)象,所以:
serviceMethod.adapt(okHttpCall)最終就是調(diào)用這個(gè)匿名對(duì)象的adapt方法
可以看到adapt方法最終就是將OkHttpCall對(duì)象轉(zhuǎn)換成了ExecutorCallbackCall對(duì)象。那這個(gè)對(duì)象能干什么?
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(); } }
可以明顯看到這個(gè)方法就是對(duì)OkHttpCall對(duì)象的一個(gè)包裝,不同的是對(duì)它的enque()方法重寫了,重寫的目的很簡單,就是為了將異步結(jié)果交給MainThreadExecutor,最終轉(zhuǎn)換到主線程執(zhí)行回調(diào)。
總結(jié)
上面源碼分析了很多,有點(diǎn)雜亂,這里我們統(tǒng)一總結(jié)下OkHttpCall到接口定義的返回類型(這里以Call<ResponseBody>為例,)的轉(zhuǎn)換過程:
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。