上一篇说到自定义Converter.Factory,那么很显然的在开发中我们也可能需要自定义CallAdapter,以实现我们的需求。例如:我们想要获取响应头信息进行某些操作,当然你可以你可以使用Response< T >或Result< T >作为响应实体类,但是如果我们这么写的话,那么在每个响应结果回调的地方都需要处理响应头,显然这是很麻烦的。因此,我们可以在CallAdapter里统一处理我们的响应头信息。
- 创建自定义的适配器工厂继承自CallAdapter.Factory;
- 创建自定义的适配器继承自CallAdapter< T >;
- 创建自定义的回调处理类CustomCall< R >。
一、创建适配器工厂
class MyCallAdapterFactory extends CallAdapter.Factory {
//这里写步骤2、3的内容和一些必要的初始化 参考RxJavaCallAdapter
//这个决定了你将采取什么样的CallAdapter
@Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
//获取returnType的原始类型 如 CustomCall<R>
Class<?> rawType = getRawType(returnType);
//返回值的类型必须是CustomCall<> 并且带有泛型
if (rawType == CustomCall.class && returnType instanceof ParameterizedType) {
//获取returnType泛型的类型 如Call<MovieDataBean>中的MovieDataBean
Type callReturnType = getParameterUpperBound(0, (ParameterizedType) returnType);
//使用CustomCallAdapter转换处理数据
return new CustomCallAdapter(callReturnType);
} else {
return null;
}
}
}
代码中的注释已经比较清晰了,不做赘述;想了解更多的请参考RxJavaCallAdapter的源码。上面代码,提到了new CustomCallAdapter(callReturnType)这就是我们的自定义CallAdapter了,下面来一段示例代码意思一下。
二、自定义的CallAdapter
/**
*其实这个类也是啥也没写 最终还是由CustomCall完成的
*/
class CustomCallAdapter implements CallAdapter<CustomCall<?>> {
private final Type responseType;
// 下面的 responseType 方法需要数据的类型
CustomCallAdapter(Type responseType) {
this.responseType = responseType;
}
@Override
public Type responseType() {
return responseType;
}
@Override
public <R> CustomCall<?> adapt(Call<R> call) {
//由我们自定义的CustomCall<> 处理数据
return new CustomCall<>(call);
}
}
CustomCall< R > 才是真正处理数据的类
//这个类只做一个大致流程的实例 没有什么实际意义
class CustomCall<R> {
public final Call<R> call;
public CustomCall(Call<R> call) {
this.call = call;
}