移步Retrofit--网络通讯框架
ExecutorCallAdapterFactory的工作
- 持有回调给用户的执行器
MainThreadExecutor
- 返回生成用户最终使用的Call对象的获取对象
CallAdapter
- 用户做网络请求的Call对象
ExecutorCallbackCall
源码分析
1. 初始化的入口
static class Android extends Platform {
...
@Override CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) {
if (callbackExecutor == null) throw new AssertionError();
return new ExecutorCallAdapterFactory(callbackExecutor);
}
...
}
ExecutorCallAdapterFactory(Executor callbackExecutor) {
this.callbackExecutor = callbackExecutor;
}
由此可知ExecutorCallAdapterFactory持有回调给用户的执行器
MainThreadExecutor
2. 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);
//返回用于生成用户最终持有的用户网络请求的Call对象
return new CallAdapter<Object, Call<?>>() {
@Override public Type responseType() {
return responseType;
}
//此处的call为真正做网络请求的OkHttpCall对象
@Override public Call<Object> adapt(Call<Object> call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
};
}
由上面代码可知CallAdapter.adapt()方法会返回
ExecutorCallbackCall
对象,而此对象是用户最终得到的用于请求的Call
3. ExecutorCallbackCall,用户最终得到的用于请求的Call
3.1 构造方法
ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
this.callbackExecutor = callbackExecutor;
this.delegate = delegate;
}
由上面代码可知ExecutorCallbackCall持有回调给用户的执行器
MainThreadExecutor
和真正做网络请求的OkHttpCall
。
所以网络执行完以后会回到UI线程内。
3.2 执行网络请求
@Override public void enqueue(final Callback<T> callback) {
checkNotNull(callback, "callback == null");
//OkHttpCall执行网络请求
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);
}
});
}
});
}
这个方法的执行是通过用户直接调用的,调用之后会进入
OkHttpCall.enqueue()
执行,然后再用回调用户执行器callbackExecutor
执行回到用户手里