Retrofit源码分析1
来源:互联网 发布:苏德战场主战场知乎 编辑:程序博客网 时间:2024/05/22 23:38
看了挺多的别人写的分析,但始终不如自己写一个记得清楚
首先:根据Retrofit的使用流程,分为3步
(1)首先是配置Retrofit的参数。这些参数有如下几种,是通过Builder模式实现的
public static final class Builder { private OkHttpClient client; private BaseUrl baseUrl; private List<Converter.Factory> converterFactories = new ArrayList<>(); private List<CallAdapter.Factory> adapterFactories = new ArrayList<>(); private Executor callbackExecutor; private boolean validateEagerly;
分别对应的方法有如下几种,也是我们配置时会用到的方法:
public Builder() { // 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());}/** The HTTP client used for requests. */public Builder client(OkHttpClient client) { this.client = checkNotNull(client, "client == null"); return this;}/** API base URL. */public Builder baseUrl(String baseUrl) { checkNotNull(baseUrl, "baseUrl == null"); HttpUrl httpUrl = HttpUrl.parse(baseUrl); if (httpUrl == null) { throw new IllegalArgumentException("Illegal URL: " + baseUrl); } return baseUrl(httpUrl);}/** API base URL. */public Builder baseUrl(final HttpUrl baseUrl) { checkNotNull(baseUrl, "baseUrl == null"); return baseUrl(new BaseUrl() { @Override public HttpUrl url() { return baseUrl; } });}/** API base URL. */public Builder baseUrl(BaseUrl baseUrl) { this.baseUrl = checkNotNull(baseUrl, "baseUrl == null"); return this;}/** Add converter factory for serialization and deserialization of objects. */public Builder addConverterFactory(Converter.Factory converterFactory) { converterFactories.add(checkNotNull(converterFactory, "converterFactory == null")); return this;}/** * TODO */public Builder addCallAdapterFactory(CallAdapter.Factory factory) { adapterFactories.add(checkNotNull(factory, "factory == null")); return this;}/** * The executor on which {@link Callback} methods are invoked when returning {@link Call} from * your service method. */public Builder callbackExecutor(Executor callbackExecutor) { this.callbackExecutor = checkNotNull(callbackExecutor, "callbackExecutor == null"); return this;}/** * When calling {@link #create} on the resulting {@link Retrofit} instance, eagerly validate * the configuration of all methods in the supplied interface. */public Builder validateEagerly() { validateEagerly = true; return this;}/** Create the {@link Retrofit} instances. */public Retrofit build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } OkHttpClient client = this.client; if (client == null) { client = new OkHttpClient(); } // Make a defensive copy of the adapters and add the default Call adapter. List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories); adapterFactories.add(Platform.get().defaultCallAdapterFactory(callbackExecutor)); // Make a defensive copy of the converters. List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories); return new Retrofit(client, baseUrl, converterFactories, adapterFactories, callbackExecutor, validateEagerly);}
其中经常用到的就是baseUrl,addConverterFactory,addCallAdapterFactory,以及build,看build最后一行,就是创建了Retrofit的对象,其中加入了client,这个是OKHttpClient的对象(默认),convertFactories是转换器比如(Gson,XML解析器),CallAdapter用到了适配器模式,这里主要包括集中(ExecutorCallAdaperFactory,RxJavaCallAdapterFactory等)这集中适配器,他们的主要作用就是封装OKHttpClient的请求和回复,顺便完成子线程和主线程之间的交互。callbackExecutor这个参数是用来记录主线程的,(RxJavaCallAdapterFactory还没有看,)在ExecutorCallAdaperFactory中,是将这个参数传递过去,从而完成主线程和子线程之间的交互的。
(2)build了以后,就需要create这个call了,这里用到了动态代理的模式:
public <T> T create(final Class<T> service) { Utils.validateServiceInterface(service); if (validateEagerly) { eagerlyValidateMethods(service); } return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service }, new InvocationHandler() { 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); } return loadMethodHandler(method).invoke(args); } });}
只要一调用Service接口中的方法,就会被动态代理类进行截取(姑且这么理解),截取了进行一些判定,重在最后一个方法,
MethodHandler<?> loadMethodHandler(Method method) { MethodHandler<?> handler; synchronized (methodHandlerCache) { handler = methodHandlerCache.get(method); if (handler == null) { handler = MethodHandler.create(this, method); methodHandlerCache.put(method, handler); } } return handler;}其中最关键的类就是MethodHandler,看下MethodHandler的源码:可以理解为method的处理类
final class MethodHandler<T> { @SuppressWarnings("unchecked") static MethodHandler<?> create(Retrofit retrofit, Method method) { CallAdapter<Object> callAdapter = (CallAdapter<Object>) createCallAdapter(method, retrofit); Type responseType = callAdapter.responseType(); Converter<ResponseBody, Object> responseConverter = (Converter<ResponseBody, Object>) createResponseConverter(method, retrofit, responseType); RequestFactory requestFactory = RequestFactoryParser.parse(method, responseType, retrofit); return new MethodHandler<>(retrofit, requestFactory, callAdapter, responseConverter); } private static CallAdapter<?> createCallAdapter(Method method, Retrofit retrofit) { Type returnType = method.getGenericReturnType(); if (Utils.hasUnresolvableType(returnType)) { throw Utils.methodError(method, "Method return type must not include a type variable or wildcard: %s", returnType); } if (returnType == void.class) { throw Utils.methodError(method, "Service methods cannot return void."); } Annotation[] annotations = method.getAnnotations(); try { return retrofit.callAdapter(returnType, annotations); } catch (RuntimeException e) { // Wide exception range because factories are user code. throw Utils.methodError(e, method, "Unable to create call adapter for %s", returnType); } } private static Converter<ResponseBody, ?> createResponseConverter(Method method, Retrofit retrofit, Type responseType) { Annotation[] annotations = method.getAnnotations(); try { return retrofit.responseConverter(responseType, annotations); } catch (RuntimeException e) { // Wide exception range because factories are user code. throw Utils.methodError(e, method, "Unable to create converter for %s", responseType); } } private final Retrofit retrofit; private final RequestFactory requestFactory; private final CallAdapter<T> callAdapter; private final Converter<ResponseBody, T> responseConverter; private MethodHandler(Retrofit retrofit, RequestFactory requestFactory, CallAdapter<T> callAdapter, Converter<ResponseBody, T> responseConverter) { this.retrofit = retrofit; this.requestFactory = requestFactory; this.callAdapter = callAdapter; this.responseConverter = responseConverter; } Object invoke(Object... args) { return callAdapter.adapt(new OkHttpCall<>(retrofit, requestFactory, responseConverter, args)); }这里的东西比较复杂,直接看调用的invoke方法,这里用到了一个callAdapter,就是通过Retrofit对象中的参数传递过去的,这里就是之前说的适配器模式,由此可知,所有的Adapter中应该都存在一个adapt的方法,方法中封装的就是OKHttpCall。
那callAdapter是怎么产生的呢
public Retrofit build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } OkHttpClient client = this.client; if (client == null) { client = new OkHttpClient(); } // Make a defensive copy of the adapters and add the default Call adapter. List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories); adapterFactories.add(Platform.get().defaultCallAdapterFactory(callbackExecutor)); // Make a defensive copy of the converters. List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories); return new Retrofit(client, baseUrl, converterFactories, adapterFactories, callbackExecutor, validateEagerly);}再回去看一下build函数,这里的build函数中默认了defaultCallAdapterFactory,并且在其中将callbackExecutor传递了进去,callbackExecutor就是指代的当前线程。其实这里的defaultCallAdapterFactory就是之前说的ExecutorCallAdapterFactory。
看下Platform中的函数,其中任然不放弃callbackExecutor,否则就没法主线程和子线程交互了
CallAdapter.Factory defaultCallAdapterFactory(Executor callbackExecutor) { if (callbackExecutor != null) { return new ExecutorCallAdapterFactory(callbackExecutor); } return DefaultCallAdapter.FACTORY;}
下面我们再看下ExecutorCallAdapterFactory的源码
final class ExecutorCallAdapterFactory implements CallAdapter.Factory { private final Executor callbackExecutor; ExecutorCallAdapterFactory(Executor callbackExecutor) { this.callbackExecutor = callbackExecutor; } @Override public CallAdapter<Call<?>> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { if (Utils.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> { private final Executor callbackExecutor; private final Call<T> delegate; ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) { this.callbackExecutor = callbackExecutor; this.delegate = delegate; } @Override public void enqueue(Callback<T> callback) { delegate.enqueue(new ExecutorCallback<>(callbackExecutor, callback)); } @Override public Response<T> execute() throws IOException { return delegate.execute(); } @Override public void cancel() { delegate.cancel(); } @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override public Call<T> clone() { return new ExecutorCallbackCall<>(callbackExecutor, delegate.clone()); } } static final class ExecutorCallback<T> implements Callback<T> { private final Executor callbackExecutor; private final Callback<T> delegate; ExecutorCallback(Executor callbackExecutor, Callback<T> delegate) { this.callbackExecutor = callbackExecutor; this.delegate = delegate; } @Override public void onResponse(final Response<T> response, final Retrofit retrofit) { callbackExecutor.execute(new Runnable() { @Override public void run() { delegate.onResponse(response, retrofit); } }); } @Override public void onFailure(final Throwable t) { callbackExecutor.execute(new Runnable() { @Override public void run() { delegate.onFailure(t); } }); } }}看get方法,得到了一个callAdapter实例,果然里面有我们的adapt方法,看它做了什么事情,就是新建了一个ExecutorCallBackCall,也就是我们最终返回得到的Call接口下的那个实例,然后我们会调用call.enqueue方法将其入队,也就是调用了这里的enqueue,
注意,adapt中有两个参数,一个就是我们之前说的指代用来指代主线程的,另外一个就是传递过来的OkHttpCall这个参数,于是这里的入队就变成了使用OKHttpCall进行入队,同时Callback用来返回给主线程
再看ExecutorCallBack中的实现,这里在主线程中将response获取返回了。
callbackExecutor.execute(new Runnable() { @Override public void run() { delegate.onResponse(response, retrofit); } });其中的请求过程以及线程都完美滴封装在了OkHttpClient中,Retrofit没有作任何事情,
只是帮助我们实现了:
(1)自动类型转换
(2)主线程和子线程通信这两个功能
- Retrofit源码分析1
- Retrofit源码分析
- Retrofit源码分析
- Retrofit源码分析
- Retrofit源码简要分析
- Retrofit源码分析
- Retrofit 源码分析
- Retrofit源码分析
- Retrofit源码分析
- Retrofit 2.0源码分析
- Retrofit 源码分析
- Retrofit源码分析
- Retrofit的源码分析
- Retrofit 源码分析
- Retrofit 源码分析流程
- Retrofit源码分析
- Retrofit 源码简单分析
- Retrofit源码分析-前
- 关于NSTimer的一些注意事项
- 三种快排及四种优化方式
- zzuli oj 1905: 小火山的跳子游戏
- Comparison of several number rounding methods
- js判断css动画是否完成 animation,transition
- Retrofit源码分析1
- Android 图片滑动,小圆点跟着滑动
- iOS中UISearchBar(搜索框)使用总结
- leetcode 8 Implement atoi to convert a string to an integer.
- 【OVS2.5.0源码分析】enqueue action精确流表生成过程分析
- HDU 1558 Segment set 并查集 线段相交
- 1019: A+B和C比大小
- linux进程优先级、进程nice值(转载)
- Gabor filter可视化项目报告