Retrofit源码解析---addConverterFactory和addCallAdapterFactory区别

我们先看下前面写的接口

Call<String> login( @Body User ueser);
如果返回的是Observable格式,则这么定义接口:

Observable<String> login(@Body User ueser);
从上面可以看到, Retrofit接口的返回值分为两部分,一部分是前面的Call或者Observable,另一部分是String。

addCallAdapterFactory影响的就是第一部分的Call或者Observable,Call类型是默认支持的(内部由DefaultCallAdapterFactory支持),而如果要支持Observable,我们就需要自己添加

  addCallAdapterFactory(RxJavaCallAdapterFactory.create())
CallAdapter会影响具体怎么执行这条请求

addConverterFactory影响的就是第二部分以及我们的请求参数,如上面的User,我们可以看下BuiltInConverters的responseBodyConverter

public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
      Retrofit retrofit) {
    if (type == ResponseBody.class) {
      if (Utils.isAnnotationPresent(annotations, Streaming.class)) {
        return StreamingResponseBodyConverter.INSTANCE;
      }
      return BufferingResponseBodyConverter.INSTANCE;
    }
    if (type == Void.class) {
      return VoidResponseBodyConverter.INSTANCE;
    }
    return null;
  }

  @Override
  public Converter<?, RequestBody> requestBodyConverter(Type type,
      Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
    if (RequestBody.class.isAssignableFrom(Types.getRawType(type))) {
      return RequestBodyConverter.INSTANCE;
    }
    return null;
  }

它只支持返回值的第二部分是ResponseBody.class和Void.class类型的或者请求参数为ResponseBody.class,我们代码中还添加了ScalarsConverterFactory和GsonConverterFactory

分别看下它们的responseBodyConverter

@Override public Converter<?, RequestBody> requestBodyConverter(Type type,
      Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
    if (type == String.class
        || type == boolean.class
        || type == Boolean.class
        || type == byte.class
        || type == Byte.class
        || type == char.class
        || type == Character.class
        || type == double.class
        || type == Double.class
        || type == float.class
        || type == Float.class
        || type == int.class
        || type == Integer.class
        || type == long.class
        || type == Long.class
        || type == short.class
        || type == Short.class) {
      return ScalarRequestBodyConverter.INSTANCE;
    }
    return null;
  }

  @Override
  public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
      Retrofit retrofit) 
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值