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



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


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


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

先是从缓存中取,如果缓存中有,则拿缓存中的ServiceMethod的对象
没有同步获取ServiceMethod对象,并存入缓存
result = new ServiceMethod.Builder<>(this, method).build();
这面是build模式进行创建,ServiceMethod对象

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

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


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



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

然后会new 一个 OkHttp对象
serviceMethod.callAdapter.adapt(okHttpCall)
返回被观察者对象

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

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


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

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

同步方法返回的Reponse要通过

进行转换我们的泛型对象,
在ServiceMethod中的toResponse进行转换

以Gson转化为例

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

observer.onNext(response);方法通知观察者
最后拿到这个泛型对象
网友评论