public interface GitHubService {
@GET("users")
Call<User> getUser(@Query("id") int userId);
}
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
service.getUser(1).enqueue(new retrofit2.Callback<User>() {
@Override
public void onResponse(retrofit2.Call<User> call, retrofit2.Response<User> response) {
}
@Override
public void onFailure(retrofit2.Call<User> call, Throwable t) {
}
});
Call:可以理解为一个完整的 http 请求活动,向服务器发起请求(Request)和得到返回结果(Response)。
CallAdapter:可以把 Call
对象转化成另一个对象,如 Observable
Converter:把数据进行转化,这个接口里面有三个转换器responseBodyConverter
,requestBodyConverter
,stringConverter
Callback:http
请求回调
public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
//设置okhttp callFactory
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
//设置executer,一般不设置使用默认的,对于Android来说就是一个使用Handler切换到主线程的executer
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
// 设置CallAdapter.factory 列表
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
// 设置 Converter.factory 列表
List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
callbackExecutor, validateEagerly);
}
可以看到,除了baseUrl 必须要添加,还有2个可选的参数。
List
和 List
用来存放传进来的参数。public <T> T create(final Class<T> service) {
Utils.validateServiceInterface(service); //1
if (validateEagerly) {
eagerlyValidateMethods(service);
}
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
//获取当前平台 这里为Android
private final Platform platform = Platform.get();
@Override public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
//获取一个ServiceMethod对象构建一个Call对象
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
使用Proxy.newProxyInstance
创建了方法接口的一个动态代理对象,调用方法的时候进入invoke
回调。
我们简单看下create
里面都做了什么
Utils.validateServiceInterface(service)
static <T> void validateServiceInterface(Class<T> service) {
if (!service.isInterface()) {
throw new IllegalArgumentException("API declarations must be interfaces.");
}
// Prevent API interfaces from extending other interfaces. This not only avoids a bug in
// Android (http://b.android.com/58753) but it forces composition of API declarations which is
// the recommended pattern.
if (service.getInterfaces().length > 0) {
throw new IllegalArgumentException("API interfaces must not extend other interfaces.");
}
}
eagerlyValidateMethods(service)
private void eagerlyValidateMethods(Class<?> service) {
Platform platform = Platform.get();
for (Method method : service.getDeclaredMethods()) {
if (!platform.isDefaultMethod(method)) {
loadServiceMethod(method);
}
}
}
由第二步可以知道,调用接口的方法,其实是调用了刚才创建的代理对象中的方法,然后进入invoke
方法。所以调用的是下面这段代码。(一般情况下是这样调用的,这里先不考虑其它情况)
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
我们分析下这段代码
ServiceMethod
ServiceMethod<?, ?> loadServiceMethod(Method method) {
ServiceMethod<?, ?> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
result = new ServiceMethod.Builder<>(this, method).build();
serviceMethodCache.put(method, result);
}
}
return result;
}
主要作用是通过反射的Method
对象获取一个ServiceMethod
对象。
首先从cache 中获取一个 ServiceMethod
,如果没有,就创建一个新的ServiceMethod
,在存入cache。
前面我们已经知道,ServiceMethod
可以进行预加载,默认使用懒加载(调用的时候加载),如果对方调用有时间要求,可以使用预先加载,减少一些时间。
下面来看ServiceMethod 的创建
public ServiceMethod build() {
callAdapter = createCallAdapter();
responseType = callAdapter.responseType();
if (responseType == Response.class || responseType == okhttp3.Response.class) {
throw methodError("'"
+ Utils.getRawType(responseType).getName()
+ "' is not a valid response body type. Did you mean ResponseBody?");
}
responseConverter = createResponseConverter();
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
if (httpMethod == null) {
throw methodError("HTTP method annotation is required (e.g., @GET, @POST, etc.).");
}
if (!hasBody) {
if (isMultipart) {
throw methodError(
"Multipart can only be specified on HTTP methods with request body (e.g., @POST).");
}
if (isFormEncoded) {
throw methodError("FormUrlEncoded can only be specified on HTTP methods with "
+ "request body (e.g., @POST).");
}
}
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler<?>[parameterCount];
for (int p = 0; p < parameterCount; p++) {
Type parameterType = parameterTypes[p];
if (Utils.hasUnresolvableType(parameterType)) {
throw parameterError(p, "Parameter type must not include a type variable or wildcard: %s",
parameterType);
}
Annotation[] parameterAnnotations = parameterAnnotationsArray[p];
if (parameterAnnotations == null) {
throw parameterError(p, "No Retrofit annotation found.");
}
parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
}
if (relativeUrl == null && !gotUrl) {
throw methodError("Missing either @%s URL or @Url parameter.", httpMethod);
}
if (!isFormEncoded && !isMultipart && !hasBody && gotBody) {
throw methodError("Non-body HTTP method cannot contain @Body.");
}
if (isFormEncoded && !gotField) {
throw methodError("Form-encoded method must contain at least one @Field.");
}
if (isMultipart && !gotPart) {
throw methodError("Multipart method must contain at least one @Part.");
}
return new ServiceMethod<>(this);
}
创建ServiceMethod
有2个参数,一个是Retrofit
对象,一个是Method
对象。
可以看到,这个方法中抛出很多异常,大部分是注解用错了。
这里主要内容有3点
我们一个个来看下:
callAdapter = 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);
}
}
(CallAdapter
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
return nextCallAdapter(null, returnType, annotations);
}
/**
* Returns the {@link CallAdapter} for {@code returnType} from the available {@linkplain
* #callAdapterFactories() factories} except {@code skipPast}.
*
* @throws IllegalArgumentException if no call adapter available for {@code type}.
*/
public CallAdapter<?, ?> nextCallAdapter(CallAdapter.Factory skipPast, Type returnType,
Annotation[] annotations) {
checkNotNull(returnType, "returnType == null");
checkNotNull(annotations, "annotations == null");
int start = adapterFactories.indexOf(skipPast) + 1;
for (int i = start, count = adapterFactories.size(); i < count; i++) {
CallAdapter<?, ?> adapter = adapterFactories.get(i).get(returnType, annotations, this);
if (adapter != null) {
return adapter;
}
}
StringBuilder builder = new StringBuilder("Could not locate call adapter for ")
.append(returnType)
.append(".\n");
if (skipPast != null) {
builder.append(" Skipped:");
for (int i = 0; i < start; i++) {
builder.append("\n * ").append(adapterFactories.get(i).getClass().getName());
}
builder.append('\n');
}
builder.append(" Tried:");
for (int i = start, count = adapterFactories.size(); i < count; i++) {
builder.append("\n * ").append(adapterFactories.get(i).getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
}
创建CallAdapter
主要调用 Retrofit
中的nextCallAdapter
,从adapterFactories
中获取一个Factory 去创建对应的 CallAdapter。如果 adapterFactories
中所有的 Factory
都无法创建对应的 CallAdapter
则会报错。
public Retrofit build() {
...
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
...
}
}
前面在创建adapterFactories
对象时,会预先在里面添加一个默认的CallAdapter.Factory
。
创建Converter 的过程和 CallAdapter 是一致的
Builder(Platform platform) {
this.platform = platform;
// Add the built-in converter factory first. This prevents overriding its behavior but also
// ensures correct behavior when using converters that consume all types.
converterFactories.add(new BuiltInConverters());
}
...
List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
...
有点不太一样的地方是在创建Retrofit.Build
对象的时候,就先把默认的Converter
也就是BuiltInConverters
添加到了converterFactories
中。
由于Retrofit
的注解比较多,所以对接口方法进行注解解析的过程比较复杂。这里简单看下:
解析注释,分两部分,一部分是解析方法上的注释,一部分是解析参数上的注释。
public ServiceMethod build() {
...
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
...
for (int p = 0; p < parameterCount; p++) {
...
parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
}
...
return new ServiceMethod<>(this);
}
parseMethodAnnotation
private void parseMethodAnnotation(Annotation annotation) {
if (annotation instanceof DELETE) {
parseHttpMethodAndPath("DELETE", ((DELETE) annotation).value(), false);
} else if (annotation instanceof GET) {
parseHttpMethodAndPath("GET", ((GET) annotation).value(), false);
} else if (annotation instanceof HEAD) {
parseHttpMethodAndPath("HEAD", ((HEAD) annotation).value(), false);
if (!Void.class.equals(responseType)) {
throw methodError("HEAD method must use Void as response type.");
}
} else if (annotation instanceof PATCH) {
parseHttpMethodAndPath("PATCH", ((PATCH) annotation).value(), true);
} else if (annotation instanceof POST) {
parseHttpMethodAndPath("POST", ((POST) annotation).value(), true);
} else if (annotation instanceof PUT) {
parseHttpMethodAndPath("PUT", ((PUT) annotation).value(), true);
} else if (annotation instanceof OPTIONS) {
parseHttpMethodAndPath("OPTIONS", ((OPTIONS) annotation).value(), false);
} else if (annotation instanceof HTTP) {
HTTP http = (HTTP) annotation;
parseHttpMethodAndPath(http.method(), http.path(), http.hasBody());
} else if (annotation instanceof retrofit2.http.Headers) {
String[] headersToParse = ((retrofit2.http.Headers) annotation).value();
if (headersToParse.length == 0) {
throw methodError("@Headers annotation is empty.");
}
headers = parseHeaders(headersToParse);
} else if (annotation instanceof Multipart) {
if (isFormEncoded) {
throw methodError("Only one encoding annotation is allowed.");
}
isMultipart = true;
} else if (annotation instanceof FormUrlEncoded) {
if (isMultipart) {
throw methodError("Only one encoding annotation is allowed.");
}
isFormEncoded = true;
}
}
方法上的注解,就是判断不同注解进行不同的解析,然后给一些变量赋值。
parseParameter
private ParameterHandler<?> parseParameter(
int p, Type parameterType, Annotation[] annotations) {
ParameterHandler<?> result = null;
for (Annotation annotation : annotations) {
ParameterHandler<?> annotationAction = parseParameterAnnotation(
p, parameterType, annotations, annotation);
if (annotationAction == null) {
continue;
}
if (result != null) {
throw parameterError(p, "Multiple Retrofit annotations found, only one allowed.");
}
result = annotationAction;
}
if (result == null) {
throw parameterError(p, "No Retrofit annotation found.");
}
return result;
}
就是把参数上的注解转化为ParameterHandler
对象,接下来看ParameterHandler
对象:
abstract class ParameterHandler<T> {
abstract void apply(RequestBuilder builder, T value) throws IOException;
final ParameterHandler<Iterable<T>> iterable() {
return new ParameterHandler<Iterable<T>>() {
@Override void apply(RequestBuilder builder, Iterable<T> values) throws IOException {
...
};
}
final ParameterHandler<Object> array() {
return new ParameterHandler<Object>() {
@Override void apply(RequestBuilder builder, Object values) throws IOException {
...
}
};
}
static final class RelativeUrl extends ParameterHandler<Object> {
@Override void apply(RequestBuilder builder, Object value) {
builder.setRelativeUrl(value);
}
}
static final class Header<T> extends ParameterHandler<T> {
...
}
static final class Path<T> extends ParameterHandler<T> {
...
}
static final class Query<T> extends ParameterHandler<T> {
...
}
static final class QueryMap<T> extends ParameterHandler<Map<String, T>> {
...
}
static final class Field<T> extends ParameterHandler<T> {
...
}
static final class FieldMap<T> extends ParameterHandler<Map<String, T>> {
...
}
static final class Part<T> extends ParameterHandler<T> {
...
}
static final class RawPart extends ParameterHandler<MultipartBody.Part> {
...
}
static final class PartMap<T> extends ParameterHandler<Map<String, T>> {
...
}
static final class Body<T> extends ParameterHandler<T> {
...
}
所有的注解对应的都有自己的一个ParameterHandler
实现。然后进行里面的解析。
解析方法注释得到的参数,以及解析方法参数的注释得到的 ParameterHandler
都是为了构建Request
对象,代码如下:
//ServiceMethod.java
Request toRequest(Object... args) throws IOException {
RequestBuilder requestBuilder = new RequestBuilder(httpMethod, baseUrl, relativeUrl, headers,
contentType, hasBody, isFormEncoded, isMultipart);
@SuppressWarnings("unchecked") // It is an error to invoke a method with the wrong arg types.
ParameterHandler<Object>[] handlers = (ParameterHandler<Object>[]) parameterHandlers;
int argumentCount = args != null ? args.length : 0;
if (argumentCount != handlers.length) {
throw new IllegalArgumentException("Argument count (" + argumentCount
+ ") doesn't match expected count (" + handlers.length + ")");
}
for (int p = 0; p < argumentCount; p++) {
handlers[p].apply(requestBuilder, args[p]);
}
return requestBuilder.build();
}
其中handlers[p].apply(requestBuilder, args[p])
循环调用ParameterHandler
这个抽象类的抽象方法。
OkHttpCall
@Override public OkHttpCall<T> clone() {
return new OkHttpCall<>(serviceMethod, args);
}
OkHttpCall的构造方法很简单,OkHttpCall实现了Call
接口。
先来看下前面默认的CallAdapter;
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
这里需要知道Platform
class Platform {
..
}
static class Android extends Platform {
@Override public Executor defaultCallbackExecutor() {
return new MainThreadExecutor();
}
@Override CallAdapter.Factory defaultCallAdapterFactory(Executor callbackExecutor) {
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
平台,所以调用Android
中的方法。
所以默认的CallAdapter.Factory
是ExecutorCallAdapterFactory
,下面我们继续刚才重要的第3句代码
return serviceMethod.callAdapter.adapt(okHttpCall)
final class ExecutorCallAdapterFactory extends CallAdapter.Factory {
...
@Override
public CallAdapter<Call<?>> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != Call.class) {
return null;
}
final Type responseType = Utils.getCallResponseType(returnType);
return new CallAdapter<Call<?>>() {
@Override public Type responseType() {
return responseType;
}
@Override public <R> Call<R> adapt(Call<R> call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
};
}
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) {
if (callback == null) throw new NullPointerException("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);
}
});
}
});
}
...
使用adapter
方法后返回ExecutorCallbackCall
这个对象
enqueue
发送请求(execute 差不多)由上面可知,调用接口方法后,真正返回的是ExecutorCallbackCall
对象。
调用enqueue
方法,其实是调用创建ExecutorCallbackCall
对象传入的Call
对象。(其实是OkhttpCall
对象)
//OkhttpCall.java
@Override public void enqueue(final Callback<T> callback) {
...
call = rawCall = createRawCall();
...
call.enqueue(new okhttp3.Callback() {
@Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
throws IOException {
...
response = parseResponse(rawResponse);
...
});
}
...
private okhttp3.Call createRawCall() throws IOException {
Request request = serviceMethod.toRequest(args);
okhttp3.Call call = serviceMethod.callFactory.newCall(request);
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
...
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
...
T body = serviceMethod.toResponse(catchingBody);
return Response.success(body, rawResponse);
...
}
其中有两个重要的方法 createRawCall
和 parseResponse
createRawCall
这里主要调用了serviceMethod.toRequest(args)
其实在前面我们知道,ServiceMethod
中的toRequest
就是把前面解析完成的参数转化为对应的Request
;
这里我们还要了解serviceMethod.callFactory
:
//ServiceMethod.java
ServiceMethod(Builder<R, T> builder) {
this.callFactory = builder.retrofit.callFactory();
...
}
//Retrofit.java
...
public Builder client(OkHttpClient client) {
return callFactory(checkNotNull(client, "client == null"));
}
/**
* Specify a custom call factory for creating {@link Call} instances.
*
* Note: Calling {@link #client} automatically sets this value.
*/
public Builder callFactory(okhttp3.Call.Factory factory) {
this.callFactory = checkNotNull(factory, "factory == null");
return this;
}
...
public Retrofit build() {
...
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
...
...
由上可看出,ServiceMethod
中的callFactory
就是Retrofit
中的callFactory
,可以在构造Retrofit
对象的时候传入,不传入默认为OkHttpClient
。
所以okhttp3.Call call = serviceMethod.callFactory.newCall(request);
这里的serviceMethod.callFactory
其实就是OkHttpClient
,然后创建了一个Call
对象。真正发起请求的也是这个Call
对象。
这里的Call
是okhttp3.call
,前面说的Call
是retrofit2.Call
,不要搞混。
其实Retrofit
可以理解为在OkHttp
外面的一层封装,真正去发生http请求的还是在okhttp里。
parseResponse
来看它里面重要的一句:
T body = serviceMethod.toResponse(catchingBody);
//ServiceMethod.java
...
this.responseConverter = builder.responseConverter;
...
T toResponse(ResponseBody body) throws IOException {
return responseConverter.convert(body);
}
...
使用Convert
对象把ResponseBody
转化为另一个对象。由代码可看出,ServiceMethod
中的responseConverter
也是来自Retrofit
对象。就是前面说的默认的converter.Factory
对象,也就是BuiltInConverters
,产生的Convert
对象。
final class BuiltInConverters extends Converter.Factory {
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
if (type == ResponseBody.class) {
return Utils.isAnnotationPresent(annotations, Streaming.class)
? StreamingResponseBodyConverter.INSTANCE
: BufferingResponseBodyConverter.INSTANCE;
}
if (type == Void.class) {
return VoidResponseBodyConverter.INSTANCE;
}
return null;
}
在ServiceMethod
中会根据方法的返回类型,在里面获得到对应的Converter
对象。如果返回的类型没有相应的Converter
则返回null。
//Retrofit.java
public <T> Converter<ResponseBody, T> nextResponseBodyConverter(Converter.Factory skipPast,
Type type, Annotation[] annotations) {
checkNotNull(type, "type == null");
checkNotNull(annotations, "annotations == null");
int start = converterFactories.indexOf(skipPast) + 1;
for (int i = start, count = converterFactories.size(); i < count; i++) {
Converter<ResponseBody, ?> converter =
//在这里真正获取对应的Converter
converterFactories.get(i).responseBodyConverter(type, annotations, this);
if (converter != null) {
//noinspection unchecked
return (Converter<ResponseBody, T>) converter;
}
}
StringBuilder builder = new StringBuilder("Could not locate ResponseBody converter for ")
.append(type)
.append(".\n");
if (skipPast != null) {
builder.append(" Skipped:");
for (int i = 0; i < start; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
builder.append('\n');
}
builder.append(" Tried:");
for (int i = start, count = converterFactories.size(); i < count; i++) {
builder.append("\n * ").append(converterFactories.get(i).getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
}
可以看出,如果返回为null,就会从下一个Converter.Factory
中获取对应的Convert
;如果没有添加Converter.Factory
,就会只有一个默认的BuiltInConverters
,并且只支持返回值为ResponseBody
、Void
这2中类型或者注释中有Streaming
的方法,否则会报错。
在前面的提到默认的CallAdapter.Factory
也就是在ExecutorCallAdapterFactory
中其实有个细节没有细看:
@Override public void enqueue(final Callback<T> callback) {
if (callback == null) throw new NullPointerException("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);
}
});
}
});
}
我们往回看,看下callbackExecutor
是什么
static class Android extends Platform {
@Override public Executor defaultCallbackExecutor() {
return new MainThreadExecutor();
}
@Override CallAdapter.Factory defaultCallAdapterFactory(Executor callbackExecutor) {
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);
}
}
}
defaultCallbackExecutor
其实就是把Runnable
抛到主线程执行。
所以在我们的Callback中的onResponse
和 onFailure
已经都是在主线程中执行了。