Retrofit自定义CallAdapterFactory

retrofit自从面世,一直很火,现在大多android开发的都在用的网络框架。我们在设置retrofit的时候需要设置CallAdapterFactory


Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.stonebangbang.com/test.php/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.creat())
                
                .build();
        return retrofit.create(apiServiceClass);



这是用rxjava自定义的adapter来实现的,我们一般都是这么用,但是如果我们要自定义calladapter的时候该怎么做呢?

现在我们来看看calladapter是干什么的

 abstract class Factory {
    /**
     * Returns a call adapter for interface methods that return {@code returnType}, or null if it
     * cannot be handled by this factory.
     */
    public abstract @Nullable CallAdapter<?, ?> get(Type returnType, Annotation[] annotations,
        Retrofit retrofit);

    /**
     * Extract the upper bound of the generic parameter at {@code index} from {@code type}. For
     * example, index 1 of {@code Map<String, ? extends Runnable>} returns {@code Runnable}.
     */
    protected static Type getParameterUpperBound(int index, ParameterizedType type) {
      return Utils.getParameterUpperBound(index, type);
    }

    /**
     * Extract the raw class type from {@code type}. For example, the type representing
     * {@code List<? extends Runnable>} returns {@code List.class}.
     */
    protected static Class<?> getRawType(Type type) {
      return Utils.getRawType(type);
    }
  }
这是一个抽象类,我们需要实现get方法,先来看看这几个方法都是干嘛的。

getParameterUpperBound
首先getParameterUpperBound方法,他是获取参数的type的,我觉得可以把它理解为获取的泛型,比如我们写了个User<T>,

我们可以new User<Man>这个man就是我们实例化的type。在看这个方法,他有两个参数,一个是index,是指位置,比如我们的User<T,V>   这个T就是0,这个V就是1,parameterizedType是个接口,继承type接口,从字面上来看是参数类型,所以我把它理解为我们定义的这个T的类型,比如man,比如我们传入的任何实例,如果我们没有传入那就不是parameterizedtype类型的。

而getRawType是提取的实例class,如果我们的User<T> 他得到的就是User.class。

而get方法是返回一个calladapter,所以我们要顶一个calladatper,再来看下calladapter,

public interface CallAdapter<R, T> {
  /**
   * Returns the value type that this adapter uses when converting the HTTP response body to a Java
   * object. For example, the response type for {
    @code Call<Repo>} is {
    @code Repo}. This type
   * is used to prepare the {
    @code call} passed to {
    @code #adapt}.
   * <p>
   * Note: This is typically not the same type as the {
    @code returnType} provided to this call
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值