Retrofit源码解析(一)
Retrofit如火如荼火遍大江南北,基本上每个Android开发者都听过或者用过,接下来我将通过项目中Retrofit代码实例和底层源码来分析Retrofit运行机制,温馨提示:阅读完此篇文章你将花费5分钟。
构建一个Retrofit
private Retrofit mRetrofit; private RetrofitUtils(){ mRetrofit = new Retrofit.Builder() .baseUrl("http://123.22.166.165:8080/api/")//换成你自己的Url .addConverterFactory(GsonConverterFactory.create())//创建一个转换工厂,将数据格式进行转换(比如JSON格式转换) .build(); }
我们可以清晰地看到Retrofit的创建采用了Build模式(构建者模式),下面让我们深入底层源码
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); }
public Builder addConverterFactory(Converter.Factory factory) { converterFactories.add(checkNotNull(factory, "factory == null")); return this; }
public Retrofit build() { if (baseUrl == null) { throw new IllegalStateException("Base URL required."); } okhttp3.Call.Factory callFactory = this.callFactory; if (callFactory == null) { callFactory = new OkHttpClient();//实际上是对OkHttp二次封装! } Executor callbackExecutor = this.callbackExecutor;//这个执行器我会后面仔细讲,很重要。 if (callbackExecutor == null) { callbackExecutor = platform.defaultCallbackExecutor();//注意这句话 } // Make a defensive copy of the adapters and add the default Call adapter. List adapterFactories = new ArrayList<>(this.adapterFactories); adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));//很重要 // Make a defensive copy of the converters. List converterFactories = new ArrayList<>(this.converterFactories); return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories, callbackExecutor, validateEagerly);//这里调用Retrofit构造方法 } }
build过程中出现了这几段代码:
Executor callbackExecutor = this.callbackExecutor; if (callbackExecutor == null) { callbackExecutor = platform.defaultCallbackExecutor(); }
在构建过程中我们看到了Executor callbackExecutor这个对象,翻译来是执行器的意思,那么这个执行器又是什么意思呢?继续看源码
public interface Executor { void execute(Runnable command);//这个执行器就是一个执行线程操作的接口}
build模式中有设置callbackExecutor的方法但是我们基本上不会设置,所以程序一般要走下面这条语句:
callbackExecutor = platform.defaultCallbackExecutor();
现在需要提起精神啦,因为激动人心的时刻马上就要来临了!
点击这个方法查看!
因为Retrofit支持的平台就是JAVA和Android,这里其实platform的值就是Android,继续执行platform.defaultCallbackExecutor方法得到的就是一个MainThreadExecutor类,这个类能干什么?看第二张图
没错这是一个Handler,主线程上的Handler,实现的方法其实就是handler.post(r),这个方法我们很常见,为什么很常见?因为遇到多很多错误,什么错误?在非主线程修改界面,所以我们使用handler.post(r)来修改UI线程界面,关于这一点如果不明白推荐下面这篇博客:
handler.post和handler.sendMessage的区别和联系
现在我们知道了callbackExecutor大概是用来执行异步任务用于刷新UI界面的,build过程继续往下走,就遇到了这句话:
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
查看源码!
return new ExecutorCallAdapterFactory(callbackExecutor);
原来返回的是ExecutorCallAdapterFactory类,这个类又有什么用呢?我们下节课再讲!
更多相关文章
- 去除svn中方法
- Android扫描zxing定制化界面实现扫描和图片解析定制ui
- android跳转微信指定公众号界面
- Android(安卓)学习笔记 databinding简单使用:使用databinding在li
- android学习日记之fragment
- android 反射应用
- android关于输入法弹出时的UI变动
- android native调用
- 【PullToRefresh 系列一基本使用方法】 Android上拉加载下拉刷新