ServiceMethod
ServiceMethod时Retrofit中的核心类,之前说的Call,CallAdapter.Factory和Convert.Factory,RequestFactory,Call.Factory都是在ServiceMethod里面的到体现。
ServiceMethod是个抽象类,子类类有抽象类HttpServiceMethod,CallAdapted,SuspendForResponse,SuspendForBody。具体来看下ServiceMethod和HttpServiceMethod
abstract class ServiceMethod<T> {
static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
//根据retrofit对象和mathod得到RequestFactory
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
Type returnType = method.getGenericReturnType();
if (Utils.hasUnresolvableType(returnType)) {
throw methodError(method,
"Method return type must not include a type variable or wildcard: %s", returnType);
}
if (returnType == void.class) {
throw methodError(method, "Service methods cannot return void.");
}
//调用HttpServiceMethod.parseAnnotations()得到ServiceMethod最终的实现类
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
abstract @Nullable T invoke(Object[] args);
}
- 根据retrofit和method得到RequesrFactory
- 调用HttpServiceMethod.parseAnnotations()
下面再看下HttpServiceMethod
//解析接口方法上的注释,构造出一个可重用的ServiceMethod来用于Http请求
//因为构造HttpServiceMethod中需要反射,因此最好每个请求方法只构建一次并且可以复用它
//重点是HttpServiceMethod对于每一个请求方法,只构建一次,再次请求相同的方法直接复用之前创建的
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
boolean continuationWantsResponse = false;
boolean continuationBodyNullable = false;
Annotation[] annotations = method.getAnnotations();
Type adapterType;
if (isKotlinSuspendFunction) {
Type[] parameterTypes = method.getGenericParameterTypes();
Type responseType = Utils.getParameterLowerBound(0,
(ParameterizedType) parameterTypes[parameterTypes.length - 1]);
if (getRawType(responseType) == Response.class && responseType instanceof ParameterizedType) {
// Unwrap the actual body type from Response<T>.
responseType = Utils.getParameterUpperBound(0, (ParameterizedType) responseType);
continuationWantsResponse = true;
} else {
// TODO figure out if type is nullable or not
// Metadata metadata = method.getDeclaringClass().getAnnotation(Metadata.class)
// Find the entry for method
// Determine if return type is nullable or not
}
adapterType = new Utils.ParameterizedTypeImpl(null, Call.class, responseType);
annotations = SkipCallbackExecutorImpl.ensurePresent(annotations);
} else {
adapterType = method.getGenericReturnType();
}
//构造出相应的CallAdapter
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
Type responseType = callAdapter.responseType();
if (responseType == okhttp3.Response.class) {
throw methodError(method, "'"
+ getRawType(responseType).getName()
+ "' is not a valid response body type. Did you mean ResponseBody?");
}
if (responseType == Response.class) {
throw methodError(method, "Response must include generic type (e.g., Response<String>)");
}
// TODO support Unit for Kotlin?
if (requestFactory.httpMethod.equals("HEAD") && !Void.class.equals(responseType)) {
throw methodError(method, "HEAD method must use Void as response type.");
}
//构造出相应的responseConverter
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);
//构造出相应的okhttp3.Call.Factory
okhttp3.Call.Factory callFactory = retrofit.callFactory;
if (!isKotlinSuspendFunction) {
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
} else if (continuationWantsResponse) {
//noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForResponse<>(requestFactory,
callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
} else {
//noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForBody<>(requestFactory,
callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
continuationBodyNullable);
}
}
- 根据retrofit上存在的CallAdapter.Factory列表,请求方法method,方法返回值的类型adapterType,注解annotations构造出相应的CallAdapter
- 根据retrofit,method,responseType构造出responseConverter
- 得到retrofit.callFactory作为自己的callFactory
上面主要是创建请求适配器,和返回数据转换器,我们详细解析下请求适配器CallAdapter的创建过程,responseConvert的创建跟CallAdapter类似
//调用retrofit.callAdapter(returnType, annotations)
private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT> createCallAdapter(
Retrofit retrofit, Method method, Type returnType, Annotation[] annotations) {
try {
//noinspection unchecked
return (CallAdapter<ResponseT, ReturnT>) retrofit.callAdapter(returnType, annotations);
} catch (RuntimeException e) { // Wide exception range because factories are user code.
throw methodError(method, e, "Unable to create call adapter for %s", returnType);
}
}
//根据请求方法的返回类型,返回相应的CallAdapter,如果没有合适的CallAdapter,那么就抛异常
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
return nextCallAdapter(null, returnType, annotations);
}
public CallAdapter<?, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
Annotation[] annotations) {
checkNotNull(returnType, "returnType == null");
checkNotNull(annotations, "annotations == null");
//因为skipPast为null,所以初始时start = 0
int start = callAdapterFactories.indexOf(skipPast) + 1;
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
//查找是否有匹配对应返回值的CallAdapter,这里就调用到CallAdapterFactory中去了
CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
if (adapter != null) {
return adapter;
}
}
//如果没有合适的CallAdapter,那么抛出异常
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(callAdapterFactories.get(i).getClass().getName());
}
builder.append('\n');
}
builder.append(" Tried:");
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
builder.append("\n * ").append(callAdapterFactories.get(i).getClass().getName());
}
throw new IllegalArgumentException(builder.toString());
}
- 从头遍历CallAdapterFactory的列表,找到符合请求返回值的请求适配器CallAdapter。如果请求的返回值为Observable,那么相应的CallAdapter就是RxJava2CallAdapter,如果请求返回值为Call,那么就是默认CallAdapter
整体请求流程
前面一篇文章和上面对于ServiceMethod的分析,已经对于Retrofit的关键类的作用有了了解,下面就结合具体的请求流程,把上面的类都串起来分析。
Retrofit时采用构建者模式构造的
private final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();//缓存ServiceMethod的表
final okhttp3.Call.Factory callFactory;//请求的构造工厂,就是OkHttpClient
final HttpUrl baseUrl;//基础Url
final List<Converter.Factory> converterFactories;//数据转换器,包括请求体,响应体的转换
final List<CallAdapter.Factory> callAdapterFactories;//请求适配器工厂列表
final @Nullable Executor callbackExecutor;//回调执行器
final boolean validateEagerly;//立即验证标志
可以看到Retrofit最重要的配置就是数据转换器和请求适配器,并且跟OkHttp强绑定。
retrofit最重要的方法就是create(),创建接口请求的实例,这里使用动态代理
public <T> T create(final Class<T> service) {
Utils.validateServiceInterface(service);
if (validateEagerly) {//如果为true,那么需要提前验证请求方法的各个注解,参数等
eagerlyValidateMethods(service);
}
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();//支持的平台,在Android 上时Android
private final Object[] emptyArgs = new Object[0];
@Override public @Nullable Object invoke(Object proxy, Method method,
@Nullable Object[] args) throws Throwable {
// If the method is a method from Object then defer to normal invocation.
//调用的方法是Object的方法,那么就正常调用
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
//是否是Platform默认的方法
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
//如果都不是上面默认的方法,那么就执行到这里
return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
}
});
}
- 提前验证的标志默认为false。如果为true的话,会提前确认好ServiceMethod,如果缓存中没有的相应的ServiceMethod,会创建ServiceMethod,并放入缓存
- 如果调用的方法是Object或者是platform的默认方法,就是不是接口的请求的方法的话,那么就走默认的方法
- 如果不满足2,那么就确认是接口的请求方法,此时就会调用loadServiceMethod,得到相应的ServiceMethod后调用invoke(),接下来详细分析
ServiceMethod<?> loadServiceMethod(Method method) {
ServiceMethod<?> result = serviceMethodCache.get(method);
if (result != null) return result;//如果缓存中有,那么就返回
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
//同步代码块,把相应ServiceMethod放入缓存
if (result == null) {
//这里就会调用ServiceMethod.parseAnnotations()
result = ServiceMethod.parseAnnotations(this, method);
serviceMethodCache.put(method, result);
}
}
return result;
}
- 检查缓存中是否有相应的ServiceMethod,如果有的话那么取出来,返回ServiceMethod
- 在同步代码块中会再次判断缓存,如果还是没有的话,就会创建ServiceMethod。这里SreviceMethod对应的是接口里的Method,对于同一个请求方法会复用同一个ServiceMethod。因为对于同一个方法来说,请求适配器CallAdpater,数据转换器ResponseConvert,还有参数的注解,肯定都是一样,只是可能每次请求参数的值不一样。 因为创建ServceMethod用到反射,复用会提高性能。
然后接着调用loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
invoke()方法是ServiceMethod的抽象方法,真正的实现是在HttpServiceMethod中,那么继续查看
@Override final @Nullable ReturnT invoke(Object[] args) {
Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);//构造出输入Retrofit的请求OkHttp,内部包装了Okhttp.Call
return adapt(call, args);//adapt()在HttpServiceMethod中是抽象方法
}
- 构造出Retrofit.Call 的实现OkHttpCall,内部封装了OkHttp.Call
- 调用adapt() ,因为HttpServiceMethod的实现类有CallAdapted,SuspendForResponse,SuspendForBody,一般都是CallAdapted,所以看下CallAdapted中的实现
CallAdapted(RequestFactory requestFactory, okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT> responseConverter,
CallAdapter<ResponseT, ReturnT> callAdapter) {
super(requestFactory, callFactory, responseConverter);
this.callAdapter = callAdapter;
}
@Override protected ReturnT adapt(Call<ResponseT> call, Object[] args) {
return callAdapter.adapt(call);//调用了CallAdapter的adaptd()
}
- 调用了callAdapter的adapt(),这里我们只追踪RxJava2CallAdapter中的实现
@Override public Object adapt(Call<R> call) {
//对Retrofit.Call 再封装,封装成适配RxJava请求Observable等...
Observable<Response<R>> responseObservable = isAsync
? new CallEnqueueObservable<>(call)
: new CallExecuteObservable<>(call);
Observable<?> observable;
if (isResult) {
observable = new ResultObservable<>(responseObservable);
} else if (isBody) {
observable = new BodyObservable<>(responseObservable);
} else {
observable = responseObservable;
}
if (scheduler != null) {
observable = observable.subscribeOn(scheduler);
}
if (isFlowable) {
return observable.toFlowable(BackpressureStrategy.LATEST);
}
if (isSingle) {
return observable.singleOrError();
}
if (isMaybe) {
return observable.singleElement();
}
if (isCompletable) {
return observable.ignoreElements();
}
return RxJavaPlugins.onAssembly(observable);
}
1.在RxJava2CallAdapterFactory 中,默认创建的是同步请求。即CallExecuteObservable
再看下同步请求CallExecuteObservable,异步请求类似,不再分析。因为现在大家都对RxJava有一定的了解,所以直接看subscribeActual()
@Override protected void subscribeActual(Observer<? super Response<T>> observer) {
// Since Call is a one-shot type, clone it for each new observer.
//这里执行了一次clone(),因为Call是一次性的请求类型,所以会为每个Observer创建新的Call
Call<T> call = originalCall.clone();
CallDisposable disposable = new CallDisposable(call);
observer.onSubscribe(disposable);
if (disposable.isDisposed()) {
return;
}
boolean terminated = false;
try {
//执行OkHttpCall的同步请求
Response<T> response = call.execute();
if (!disposable.isDisposed()) {
//传递给观察者
observer.onNext(response);
}
if (!disposable.isDisposed()) {
terminated = true;
observer.onComplete();
}
} catch (Throwable t) {
Exceptions.throwIfFatal(t);
if (terminated) {
RxJavaPlugins.onError(t);
} else if (!disposable.isDisposed()) {
try {
observer.onError(t);
} catch (Throwable inner) {
Exceptions.throwIfFatal(inner);
RxJavaPlugins.onError(new CompositeException(t, inner));
}
}
}
}
- 对于OkHttpCall执行一次clone(),因为OkHttpCall是一种一次性的类型,只能执行一次请求,所以需要clone(),为每个Observer创建新的请求
- 执行OkHttpCall的同步请求,得到Retrofit.Response
- 传递给Observer
这时候就串起来了,当调用请求方法获得Observable时,调用subscribe(),触发网络请求。
网友评论