之前在Retrofit源碼初探一文中我們提出了三個(gè)問題:
成都創(chuàng)新互聯(lián)公司2013年至今,先為迪慶州等服務(wù)建站,迪慶州等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為迪慶州企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
其中前兩個(gè)問題在前幾篇文章已經(jīng)做了解答,今天我們探究下最后一個(gè)問題:
我們定義接口時(shí),有這樣的:
@GET("hello/world") CallgetNews(@Query("num") String num,@Query("page")String page);
也有這樣的:
@GET("book/search") ObservablegetSearchBook(@Query("q") String name, @Query("tag") String tag, @Query("start") int start, @Query("count") int count);
可以看到接口的返回值是不一樣的,現(xiàn)在我們就來分析下,一個(gè)OkHttpCall對象是如何轉(zhuǎn)換成對應(yīng)的返回值的。
核心代碼是這句:
return serviceMethod.adapt(okHttpCall);
進(jìn)到adapt中去:
T adapt(Callcall) { return callAdapter.adapt(call); }
可以看到是調(diào)用了callAdapter.adapt方法,此處的callAdapter是一個(gè)接口類型,所以想要看它的adapt方法的具體實(shí)現(xiàn)就得看這個(gè)callAdapter具體怎么生成的。
經(jīng)過搜索,發(fā)現(xiàn)它的生成方式如下:
ServiceMethod(Builderbuilder) { //……………… 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 CallAdaptercreateCallAdapter() { 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 ) 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,所以繼續(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è)直接返回。
對于默認(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. ListcallAdapterFactories = new ArrayList<>(this.callAdapterFactories); callAdapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor)); //省略部分代碼 return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories), unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly); }
這里有一點(diǎn)要事先說下,所有的CalllAdapter對象其實(shí)都是通過CallAdapter.Factory對象調(diào)用get()方法生成的。
所以這里利用platform.defaultCallAdapterFactory()生成了一個(gè)對應(yīng)的CallAdapter.Factory對象,但生成這個(gè)對象首先生成了一個(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平臺的,可以看到這里生成的callbackExecutor的execute()方法主要就是用來將操作發(fā)送到主線程執(zhí)行。
ok,callbackExecutor我們弄清楚了,那么接下來我們繼續(xù)看platform.defaultCallAdapterFactory()方法生成了什么樣的CallAdapter.Factory對象:
CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) { if (callbackExecutor != null) { return new ExecutorCallAdapterFactory(callbackExecutor); } return DefaultCallAdapterFactory.INSTANCE; }
對于Android平臺來說,我們之前生成了一個(gè)對應(yīng)的callbackExecutor,所以我們繼續(xù)跟進(jìn)if中的語句,發(fā)現(xiàn)最終生成了一個(gè)ExecutorCallAdapterFactory()對象,當(dāng)然,我們主要是看它的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
這個(gè)get()方法生成了一個(gè)匿名的CallAdapter對象,所以:
serviceMethod.adapt(okHttpCall)最終就是調(diào)用這個(gè)匿名對象的adapt方法
可以看到adapt方法最終就是將OkHttpCall對象轉(zhuǎn)換成了ExecutorCallbackCall對象。那這個(gè)對象能干什么?
static final class ExecutorCallbackCallimplements Call { final Executor callbackExecutor; final Call delegate; ExecutorCallbackCall(Executor callbackExecutor, Call delegate) { this.callbackExecutor = callbackExecutor; this.delegate = delegate; } @Override public void enqueue(final Callback callback) { checkNotNull(callback, "callback == null"); delegate.enqueue(new Callback () { @Override public void onResponse(Call call, final Response 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 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 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 clone() { return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone()); } @Override public Request request() { return delegate.request(); } }
可以明顯看到這個(gè)方法就是對OkHttpCall對象的一個(gè)包裝,不同的是對它的enque()方法重寫了,重寫的目的很簡單,就是為了將異步結(jié)果交給MainThreadExecutor,最終轉(zhuǎn)換到主線程執(zhí)行回調(diào)。
總結(jié)
上面源碼分析了很多,有點(diǎn)雜亂,這里我們統(tǒng)一總結(jié)下OkHttpCall到接口定義的返回類型(這里以Call
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。