为了账号安全,请及时绑定邮箱和手机立即绑定

Retrofit 源码解析

标签:
Redis

以Rereofit+Rxjava及Gson的转换进行讲解
首先


webp

image.png

webp

image1.png

webp

image2.png


基本的网络请求形成了,当调用
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
这两个方法的时候
Retrofit会进行adpter和converter的添加


webp

image3.png

webp

image4.png


添加到自己的集合中。
重点是Retrofit的create()方法


webp

image5.png


webp

image6.png


这个方法运用到了动态代理,当去调用Retrofit  接口类的方法时候会代理调用invoke()方法, reture CallAdapter转化的对象
这里面主要是
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
loadServiceMethod(method)方法


webp

image7.png


先是从缓存中取,如果缓存中有,则拿缓存中的ServiceMethod的对象
没有同步获取ServiceMethod对象,并存入缓存

result = new ServiceMethod.Builder<>(this, method).build();
这面是build模式进行创建,ServiceMethod对象


webp

image8.png


分别是方法,方法的注解,参数的类型,参数注解的数组


webp

image9.png


这面则对callAdapter, responseType,responseConverter进行赋值

webp

image21.png

webp

image22.png


只要循环出一个converter转化器就会跳出循环

webp

image23.png

webp

image24.png

webp

image25.png


只要循环出一个adapter就会跳出循环

webp

image6.png


然后会new 一个 OkHttp对象

serviceMethod.callAdapter.adapt(okHttpCall)
返回被观察者对象


webp

image11.png


订阅观察者
当执行subscribe()订阅这个方法的时候会触发


webp

image12.png


CallExecuteObservable的subsribeActual()方法
通过同步execute执行请求

webp

image13.png


webp

image14.png


通过  call = rawCall = createRawCall(); 拿到这个请求


webp

image15.png

Request request = serviceMethod.toRequest(args);
这个方法则是建一个请求 get请求则是拼参
post请求则是以表单形式添加请求体,对请求进行封装。

okhttp3.Call call = serviceMethod.callFactory.newCall(request);

webp

image16.png

同步方法返回的Reponse要通过


webp

image17.png


进行转换我们的泛型对象,

在ServiceMethod中的toResponse进行转换


webp

image18.png


以Gson转化为例


webp

image20.png

然后回掉到CallExecuteObservable 被观察者类中的


webp

image19.png



作者:MrLgc
链接:https://www.jianshu.com/p/78d2878e994c


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
手记
粉丝
172
获赞与收藏
955

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消