之前在Retrofit源码初探一文中我们提出了三个问题:
- 什么时候开始将注解中参数拼装成http请求的信息的?
- 如何产生发起http请求对象的?
- 如何将对象转换成我们在接口中指定的返回值的?
其中前两个问题在前几篇文章已经做了解答,今天我们探究下最后一个问题:
我们定义接口时,有这样的:
1
2
|
@GET ( "hello/world" )
Call<News> getNews( @Query ( "num" ) String num, @Query ( "page" )String page);
|
也有这样的:
1
2
3
4
|
@GET ( "book/search" )
Observable<Book> getSearchBook( @Query ( "q" ) String name,
@Query ( "tag" ) String tag, @Query ( "start" ) int start,
@Query ( "count" ) int count);
|
可以看到接口的返回值是不一样的,现在我们就来分析下,一个OkHttpCall对象是如何转换成对应的返回值的。
核心代码是这句:
1
|
return serviceMethod.adapt(okHttpCall);
|
进到adapt中去:
1
2
3
|
T adapt(Call<R> call) {
return callAdapter.adapt(call);
}
|
可以看到是调用了callAdapter.adapt方法,此处的callAdapter是一个接口类型,所以想要看它的adapt方法的具体实现就得看这个callAdapter具体怎么生成的。
经过搜索,发现它的生成方式如下:
1
2
3
4
5
|
ServiceMethod(Builder<R, T> builder) {
//………………
this .callAdapter = builder.callAdapter;
//………………
}
|
而这个构造方法是在ServiceMethod.Builder的build方法中调用的:
1
2
3
4
5
|
public ServiceMethod build() {
callAdapter = createCallAdapter();
//…………
return new ServiceMethod<>( this );
}
|
所以继续跟进createCallAdapter()中去:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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中去:
1
2
3
|
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
return nextCallAdapter( null , returnType, annotations);
}
|
继续进到nextCallAdapter中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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生成时默认加上的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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,我们先看下它是怎么回事:
1
2
3
|
@Nullable Executor defaultCallbackExecutor() {
return null ;
}
|
咦,为什么是返回null的?别慌,Retrofit的build中的platform根据不同的情况会是不同的子类,并不一定是Platform的实例,而是它的子类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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对象:
1
2
3
4
5
6
|
CallAdapter.Factory defaultCallAdapterFactory( @Nullable Executor callbackExecutor) {
if (callbackExecutor != null ) {
return new ExecutorCallAdapterFactory(callbackExecutor);
}
return DefaultCallAdapterFactory.INSTANCE;
}
|
对于Android平台来说,我们之前生成了一个对应的callbackExecutor,所以我们继续跟进if中的语句,发现最终生成了一个ExecutorCallAdapterFactory()对象,当然,我们主要是看它的get()方法能得到什么样的CallAdapter对象:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@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对象。那这个对象能干什么?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
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>为例,)的转换过程:
- 通过platform(在Android平台上是它的子类Android) 生成一个Executor对象,在Android上就是MainThreadExecutor对象。
- 通过platform生成一个CallAdapterFactory对象,在Android上就是ExecutorCallAdapterFactory对象,该对象能通过get()方法生成一个CallAdapter对象,来将OkHttpCall对象转成ExecutorCallbackCall对象。
- 将上面提到的CallAdapterFactory对象塞到Retrofit对象中,最终在ServiceMethod的adapt()方法中调用,将OkHttpCall转成ExecutorCallback,然后就可以正常的调用enque()方法发起请求了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。