Retrofit源码之请求对象的转换笔记
时间:2022-06-25 22:58:35 编辑:袖梨 来源:一聚教程网
之前在Retrofit源码初探一文中我们提出了三个问题:
- 什么时候开始将注解中参数拼装成http请求的信息的?
- 如何产生发起http请求对象的?
- 如何将对象转换成我们在接口中指定的返回值的?
其中前两个问题在前几篇文章已经做了解答,今天我们探究下最后一个问题:
我们定义接口时,有这样的:
@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);
可以看到接口的返回值是不一样的,现在我们就来分析下,一个OkHttpCall对象是如何转换成对应的返回值的。
核心代码是这句:
return serviceMethod.adapt(okHttpCall);
进到adapt中去:
T adapt(Callcall) { return callAdapter.adapt(call); }
可以看到是调用了callAdapter.adapt方法,此处的callAdapter是一个接口类型,所以想要看它的adapt方法的具体实现就得看这个callAdapter具体怎么生成的。
经过搜索,发现它的生成方式如下:
ServiceMethod(Builderbuilder) { //……………… this.callAdapter = builder.callAdapter; //……………… }
而这个构造方法是在ServiceMethod.Builder的build方法中调用的:
public ServiceMethod build() { callAdapter = createCallAdapter(); //………… return new ServiceMethod<>(this); }
所以继续跟进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,所以继续跟到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. ListcallAdapterFactories = 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