基于Retrofit:3.12.0:https://github.com/square/retrofit/tree/parent-2.5.0
Read The Fucking Source Code
@NonNull
protected Retrofit.Builder createBuilder() {
return new Retrofit.Builder().baseUrl(apiBaseUrl())
.addConverterFactory(GsonConverterFactory.create(GsonUtils.getGson()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.client(okHttpClient());
}
//原始call形式
Call api1=Retrofit#create(final Class service).api()
api1.enqueue(Callback)
//Rxjava形式
Obserable api2=Retrofit#create(final Class service).api()
api2.subscibe{T t}
throw new IllegalArgumentException("API declarations must be interfaces.")
。接着执行是否提前初始化缓存该接口中所有的API方法。即使我们没有看下面的代码,也可以猜测出会和下面的方法有部分逻辑重合,因为"提前"初始化。先跳过提前初始化这一块逻辑,因为是个性化业务。直接看重点动态代理。注意:InvocationHandler#invoke的返回值就是我们定义的API的返回:Call或者Obserable,所以loadServiceMethod(method).invoke(args != null ? args : emptyArgs)
=>ServiceMethod#invoke的返回值也就是Call或者Obserable,后面分析会用到。//Retrofit
public T create(final Class service) {
//检测service是否是接口,不是直接抛异常
Utils.validateServiceInterface(service);
//是否提前遍历缓存service中所有的接口
if (validateEagerly) {
eagerlyValidateMethods(service);
}
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class>[] { service },
new InvocationHandler() {
@Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
//其它辅助代码...
//核心入口:返回值就是我们定义的API的返回值
return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
}
});
}
Proxy.newProxyInstance(ClassLoader loader,Class>[] interfaces,InvocationHandler h)
public interface InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
}
ServiceMethod.parseAnnotations(this, method)
是核心,那会做些什么?根据名字可以猜测:解析参数、注解、返回值…继续看,是否和我们猜测一致。 //Retrofit
ServiceMethod> loadServiceMethod(Method method) {
//看缓存中是否存在,存在直接返回
ServiceMethod> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
//核心入口,只看这里就好
result = ServiceMethod.parseAnnotations(this, method);
serviceMethodCache.put(method, result);
}
}
return result;
}
abstract class ServiceMethod {
static ServiceMethod parseAnnotations(Retrofit retrofit, Method method) {
//根据method解析method参数、注解、返回值生成RequestFactory对象
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
//这里先不看,下面再分析...
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
}
RequestFactory#Builder
RequestFactory build() {
//解析方法上面的注解
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
//...
//解析方法参数中的注解
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler>[parameterCount];
for (int p = 0; p < parameterCount; p++) {
parameterHandlers[p] = parseParameter(p, parameterTypes[p], parameterAnnotationsArray[p]);
}
//...
return new RequestFactory(this);
}
RequestFactory#Builder
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);
} ...其它类型的请求
}
//解析参数注解,要遍历每个参数,因为每个参数都可能有注解
private ParameterHandler> parseParameter(
int p, Type parameterType, @Nullable Annotation[] annotations) {
ParameterHandler> result = null;
if (annotations != null) {
for (Annotation annotation : annotations) {
ParameterHandler> annotationAction =
parseParameterAnnotation(p, parameterType, annotations, annotation);
...
}
...
return result;
}
//解析参数注解:贼长的遍历解析,写框架不仅需要架构经验,还是一个体力活
@Nullable
private ParameterHandler> parseParameterAnnotation(
int p, Type type, Annotation[] annotations, Annotation annotation) {
if (annotation instanceof Url) {
...
} else if (annotation instanceof Path) {
...
} else if (annotation instanceof Query) {
...
} else ...
return null; // Not a Retrofit annotation.
}
#ServiceMethod
abstract class ServiceMethod {
static ServiceMethod parseAnnotations(Retrofit retrofit, Method method) {
//上一步有分析
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
//...
//入口,生成HttpServiceMethod对象
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
}
//HttpServiceMethod#parseAnnotations
static HttpServiceMethod parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
//重点:入口
CallAdapter callAdapter = createCallAdapter(retrofit, method);
//...
//根据callAdapter构建Converter包装类
Converter responseConverter =
createResponseConverter(retrofit, method, responseType);
okhttp3.Call.Factory callFactory = retrofit.callFactory;
//构建HttpServiceMethod
return new HttpServiceMethod<>(requestFactory, callFactory, callAdapter, responseConverter);
}
//HttpServiceMethod
private static CallAdapter createCallAdapter(
Retrofit retrofit, Method method) {
Type returnType = method.getGenericReturnType();
//根据返回值获取CallAdapter
return (CallAdapter) retrofit.callAdapter(returnType, annotations);
}
//Retrofit
public CallAdapter, ?> callAdapter(Type returnType, Annotation[] annotations) {
return nextCallAdapter(null, returnType, annotations);
}
// Retrofit
public CallAdapter, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
Annotation[] annotations) {
//...
//遍历callAdapterFactories,这个是我们设置retrofit的时候Retrofit#Builder#addCallAdapterFactory
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;
}
}
//...
}
//ServiceMethod
abstract class ServiceMethod {
//动态代理最后调用的方法
abstract T invoke(Object[] args);
}
final class HttpServiceMethod extends ServiceMethod {
//最终动态代理调用的方法
@Override ReturnT invoke(Object[] args) {
return callAdapter.adapt(
new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
}
}
//RxJava2CallAdapter,这是一个CallAdapter其中的一个实现
final class RxJava2CallAdapter implements CallAdapter {
@Override public Object adapt(Call call) {
//这里取做真正的调用
Observable> 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);
}
}
final class CallEnqueueObservable extends Observable> {
private final Call originalCall;
CallEnqueueObservable(Call originalCall) {
this.originalCall = originalCall;
}
@Override protected void subscribeActual(Observer super Response> observer) {
// Since Call is a one-shot type, clone it for each new observer.
Call call = originalCall.clone();
CallCallback callback = new CallCallback<>(call, observer);
observer.onSubscribe(callback);
if (!callback.isDisposed()) {
//最后的call API
call.enqueue(callback);
}
}