Android Retrofit的源码解读
先提出几个问题,然后本片文章就根据下面几个问题做源码的解读。
1.整个请求的流程是怎样的?
2.底层是如何用 OkHttp 请求的?
3.Okhttp是异步的,retrofit是怎么帮我们切换到主线程的
4.注解是什么时候解析的,怎么解析的?
5.Converter和CallAdapter的作用
6.如何支持 Kotlin协程的suspend挂起函数的?
Retrofit的简单流程图

接下来就根据流程图进入,首先是Retrofit.build()

重点1
因为我们一般都不会传入callbackExecutor(回调执行器),所以他会进入到platform.defaultCallbackExecutor()语句
但是我们直接点进去看的话,会发现,啥也没有

那就先从platform入手吧,进入之后能看到
(其实英语也知道platform就是平台的意思,这里就是做一个平台的区分)

接着再进入Android()

所以这里可以认为callbackExecutor == MainThreadExecutor
,用来切换线程
重点2
可以看到上一步拿到的callbackExecutor 作为参数传入了platform.defaultCallAdapterFactories(callbackExecutor)
,进入看到

接着进入DefaultCallAdapterFactory

在进入ExecutorCallbackCall

这就是发起网络请求后,Retrofit帮我们切换到主线程的流程,总得来说就是在build
方法中,通过Platform
的子类Android()
添加了一个默认的Executor:MainThreadExecutor
,然后还添加了一个DefaultCallAdapterFactory
并创建了匿名内部类CallAdapter
将MainThreadExecutor
,包装成ExecutorCallbackCall
,在网络请求回调,通过它切换线程,并把结果抛出去
重点3

如果你没添加ConverterFacTory的话,默认会通过这个转换数据,你也可以通过继承Converter.FacTory自定义自己的数据转换。Gson的就是这样做的。
接着Retrofit.create()
这个方法看起来很简单就是通过动态代理获取interface的实例,接着你就可以调用方法了
当我们通过实例调用方法时,就会进入InvocationHandler.invoke
,重点在这里面

先进入到看一看ServiceMethod
进入loadServiceMethod
,
方法很简单,就是先从自己保存的中查找,没有则生成再保存下来,以后可以复用。


先看一下RequestFactory
,里面都是方法注解的处理。需要注意的是对kotlin协程的适配
在RequestFactory的build方法中
,会遍历所有参数,去解析他们

在跟进到parseParameter
,我们知道kotlin在编译时候,会给方法最后后面添加一个Continuation<T>
的参数,

而这个标志位会保存在requestFactory
然后传入HttpServiceMethod
!!这里写错了,这里responseType应该是Continuation里面的泛型<T>!!


1.先看第一个,普通方法进入的CallAdapted
写错了,应该是loadServiceMethod(method).invoke()
调用的


2.当是一个suspend方法时


interface.enqueue
在调用apiService.getHttp() 接口的方法
其实就是在调用 --> InvocationHan.invoke()
最终就是 --> return loadServiceMethod(method).invoke()
在跟进代码之后,

所以又回到了DafalutCallAdapterFactory

看到OkHttpCall的方法

这是真正的创建OkHttp的Call

拿到Okhttp的call后就可以网络请求了
