从 ServiceMethod 开始理解 retrofit

smaillift 2019-06-27

导读:

本文将带着你,从请求执行的角度,以 interface 中我们定义的方法为起始,解读 retrofit 的执行流程。目的是想让我们对 retrofit 的执行流程有一个框架性的了解,同时也是为了面试的时候,可以跟面试官“有的聊”。

ServiceMethod

retrofit的核心思想是将 http 请求过程抽象成了一个对象 ServiceMethod。 这个对象的构造的时候,会通过 java 反射的方式传入一个 method 对象,而这个对象就是我们在 interface 中定义的请求方法。通过对 method 对象 find usage ,我们可以发现,一共有两处使用了这个 method 对象:

  • ServiceMethod.createCallAdapter()

    • getGenericReturnType()
    • getAnnotations()
  • ServiceMethod.createResponseConverter()

    • getAnnotations()

可以看到,里面使用了 method 对象的两个关键信息:注解和返回类型。而其中涉及的两个方法则同时出现在了 ServiceMethod.build() 中。

public ServiceMethod build() {
      callAdapter = createCallAdapter();
      responseConverter = createResponseConverter();
    }

至此,我们已经找到了 retrofit 的精妙所在:

  1. 通过 method 的 returnType 构造出 createCallAdapter 和 responseConverter,然后自动的完成从服务器的返回结果,到程序用的 model 类实例的转换。
  2. 通过 annotation 定义网络请求相关的参数。

annotation 的解析是一个简单但繁琐的工作,需要对每一个注解逐个判断。因此我们把重点放在 callAdapter 和 responseConverter 的分析上。而我在阅读相关代码的过程中,发现其中的泛型部分对我们理解整个框架造成了很大的阻碍。因此,想理解 retrofit,必须要弄懂其各个泛型类的意义,不然看一看就自己把自己绕晕了。

从类型系统的角度看 retrofit

  • Service<R, T>
  • CallAdapter<R, T>
  • Tadapt(Call<R> call)
  • Response<R> parseResponse(okhttp3.Response rawResponse)

抽象的太复杂,不如我们举个例子。比如,我们想从服务器请求电台相关的数据,那么,我们的请求方法定义就可能是下面这样

@GET("/albums")
RadioCall<RadioAlbumModel> getAlbums():

其中返回类型中涉及两个自定义的部分:RadioCall 和 RadioAlbumModel。其中,RadioAlbumModel 是我们定义的model 类,一般用 gson 解析服务器的数据并创建实例;RadioCall extends Call,并将请求等委托给实际的 call 对象。

往我们的泛型中套用一下,

  • T就是 RadioCall<RadioAlbumModel>
  • R就是 RadioAlbumModel
  • adapt 的作用是把 retrofit2.Call<RadioAlbumModel> 转化为 RadioCall<RadioAlbumModel>

继续把上面四个泛型类具化:

  • Service<RadioAlbumModel, RadioCall<RadioAlbumModel>>
  • CallAdapter<RadioAlbumModel, RadioCall<RadioAlbumModel>>
  • RadioCall<RadioAlbumModel> adapter(Call<RadioAlbumModel> call)
  • Response<RadioAlbumModel> parseResponse(okhttp3.Response rawResponse)

这样,请求的执行流程就呼之欲出了:

首先,调用端的调用代码应该是这样的:

RadioCall<RadioAlbumModel> radioCall = retrofitClient.getAlbums();
radioCall.execute()

其中,getAlbums() 就是我们的 method 方法。根据这个 method 方法, 生成 ServiceMethod 对象,返回的结果是 serviceMethod.callAdapter.adapt(okHttpCall); 。而我们知道,我们在 interface 中定义的 getAlbums() 的返回类型恰好是 RadioCall<RadioAlbumModel>,两个类型就这么对上了。

在radioCall.execute() 的内部,我们会把调用 delegates.execute() 来实际执行网络请求。这个 delegates 的类型就是 retrofit.OkHttpCall。然后,发起请求,等待服务器返回结果,并对结果进行处理。注意,此时的结果还是 rawResponse,即都是 json 字符串,还不是可以直接使用的 java model 对象。这个时候,我们就需要 responseConverter 来帮我们进行转换了。

在获取到结果之后,我们会调用 Response<T> retrofit2.OkHttpCall.parseResponse(okhttp3.Response rawResponse) 中,进而调用如下代码

//------ in OkHttpCall.java
  Response<R> parseResponse(okhttp3.Response rawResponse) throws IOException {
      R body = serviceMethod.toResponse(cachingBody);
      return Response.success(body, rawResponse);
  }


//------ in ServiceMethod.java
  /** Builds a method return value from an HTTP response body. */
  R ServiceMethod.toResponse(ResponseBody body) throws IOException {
    return responseConverter.convert(body);
  }

正如我们上文所说,RadioCall 一般会把一个 okHttpCall 作为构造函数的参数,然后把实际请求委托给 okHttpCall,然后再 onResposne 回调中就能得到上面代码中的 Response<R>,将我们的类带入,就是 Response<RadioAlbumModel>。而这个,就是 execute() 的执行结果。然后我们就可以得到 Response<RadioAlbumModel> 中的 model 对象了。

至此,retrofit 的请求执行流程就分析完毕。最后我们再从宏观的角度,从面试的角度,来阐述一下整个执行过程。

面向面试编程:

问:请简述 retrofit 中,一个方法的执行流程。

答:

首先我们通过我们 create 出来的 retrofit 实例来调用接口方法。所有的 interface 方法都会在 java 动态代理机制的作用下,调用一个匿名类 new InvocationHandler 中的 invoke。在 invoke 中,会根据我们想调用的方法 method 构造出一个 serviceMethod,然后调用 serviceMethod.callAdapter.adapt(okHttpCall) 作为返回结果。

构造 serviceMethod 的时候,会根据 interface 中 method 的的返回类型,构造出 converter 和 callAdapter。其中, converter 一般使用 gson converter。gson converter 可以自动将服务器返回的 json 数据转化成 java 中的 model 类的实例。callAdapter 绝大多数的实现方式是在构造函数中接收一个 okHttpCall 实例,然后将 enqueue 和 execute 委托给这个 okHttpCall 实例来执行。okHttpCall 在获取到服务器数据之后,会利用 serviceMethod.toResponse(body) 来对数据进行转化。其中,转化的时候便利用了 converter。数据转化完成后,封装成 Response<R> ,传递给调用方。其中 R 就是我们的数据类。

补充:返回类型知识点复习

关于返回类型getGenericReturnType(),会调用到下面的方法:

Type getCallResponseType(Type return)  {
    getParameterUpperBound(0, returnType)    
}

这个方法的作用就是获取实际类型。比如,如果一个方法如下:

List<String> get() {
    return ArrayList()
}

其返回类型是List<String>,那么,getCallResponseType(method.genericReturnType) 得到的结果就是 String 。其中,method.returnType 为 java.util.List,mehod.genericReturnType 为 java.util.List<String>。

相关推荐