美文网首页
Retrofit2.5.0解析

Retrofit2.5.0解析

作者: ukyoo | 来源:发表于2019-05-23 20:37 被阅读0次

    Retrofit是非常知名的轮子了, 几年之前很火的就是Retrofit + Rxjava了.
    相比单独的OkHttp,多了很多扩展. 能高度扩展, 我们想到的肯定是面向接口编程了.

    网上的版本大多比较旧,下个最新版的看一下.基于最新版本2.5.0

    1.基本用法

    1.1 创建Retrofit对象,可以看到这里使用了builder模式

    var commonClient = Retrofit.Builder()
            .baseUrl(NetWorkConstant.PORT_URL)
            .client(getHttpClient(COMMON_HEAD))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
    

    1.2 定义API接口,通过Retrofit对象创建并调用API

    //定义API接口标准, 路径,入参, 回参
    interface ApiService{
        @GET("restful/login")
        fun login(@QueryMap params: Map<String, String>): Flowable<ApiResponse<LoginResultDTO>>
    }
    
    //创建API实例
    val apiService = NetworkManager.getCommonClient().create(ApiService::class.java);
    
    //调用接口
    apiService.login(params)
    

    重点是第二步创建ApiService实例
    val apiService = NetworkManager.getCommonClient().create(ApiService::class.java)
    查看实现

      public <T> T create(final Class<T> service) {
        Utils.validateServiceInterface(service);
        if (validateEagerly) {
          eagerlyValidateMethods(service);
        }
        return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
            new InvocationHandler() {
              private final Platform platform = Platform.get();
              private final Object[] emptyArgs = new Object[0];
    
              @Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
                  throws Throwable {
                // If the method is a method from Object then defer to normal invocation.
                //如果是Object的方法,直接反射调用
                if (method.getDeclaringClass() == Object.class) {
                  return method.invoke(this, args);
                }
                //如果是JDK8的default方法,直接反射调用default方法
                if (platform.isDefaultMethod(method)) {
                  return platform.invokeDefaultMethod(method, service, proxy, args);
                }
                //这里才是我们自己定义的方法被调用
                return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
              }
            });
      }
    

    看到返回值是Proxy.newProxyInstance()动态代理把接口的方法转发给InvocationHandlerinvoke()方法内部调用.
    可以看到Retrofit先处理了Object提供的方法和JDK8新增的default方法.都不是才执行这一行调用我们自己定义的业务方法.

    return loadServiceMethod(method).invoke(args != null ? args : emptyArgs)
    

    2. ServiceMethod

    loadServiceMethod(method).invoke(args != null ? args : emptyArgs)分为两步

    2.1 loadServiceMethod(method)

    可以看到这里使用ConcurrentHashMap<Method,ServiceMethod>来缓存每个Method对应的SericeMethod对象.如果有缓存直接读取缓存,没有就调用ServiceMethod.parseAnnotations(this, method)创建新的SericeMethod

      //ConcurrentHashMap来缓存method, Concurrent包通过CAS解决线程情况下的资源竞争
      private final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();
    
      ServiceMethod<?> loadServiceMethod(Method method) {
        ServiceMethod<?> result = serviceMethodCache.get(method);
        if (result != null) return result;
    
        synchronized (serviceMethodCache) {
          result = serviceMethodCache.get(method); //有缓存就用缓存
          if (result == null) {  //没有缓存就根据当前method创建一个ServiceMethod对象,存入Map
            result = ServiceMethod.parseAnnotations(this, method);
            serviceMethodCache.put(method, result);
          }
        }
        return result;
      }
    

    2.2 ServiceMethod.parseAnnotations(this, method)

    abstract class ServiceMethod<T> {
      static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
        //1. 创建RequestFactory对象
        RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
    
        Type returnType = method.getGenericReturnType();
        if (Utils.hasUnresolvableType(returnType)) {
          //如果方法的返回值没有类型或者通配符,抛出异常
          throw methodError(method,
              "Method return type must not include a type variable or wildcard: %s", returnType);
        }
        if (returnType == void.class) {  //返回是void也会抛出异常
          throw methodError(method, "Service methods cannot return void.");
        }
        //2. 交给他的子类HttpServiceMethod去实现
        return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
      }
    
      abstract T invoke(Object[] args);
    }
    
    1. RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method); 这里通过建造者模式构建了一个RequestFactory对象
    final class RequestFactory {
      static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
        return new Builder(retrofit, method).build();
      }
    
      RequestFactory(Builder builder) {
        method = builder.method;    //方法
        baseUrl = builder.retrofit.baseUrl; //baseUrl
        httpMethod = builder.httpMethod;//POST,GET,DELETE...
        relativeUrl = builder.relativeUrl;// baseUrl+后缀
        headers = builder.headers; // http header
        contentType = builder.contentType; //http contentType
        hasBody = builder.hasBody; //POST请求使用
        isFormEncoded = builder.isFormEncoded; //application/x-www-form-urlencoded 是否默认转码
        isMultipart = builder.isMultipart; //标记是否是MultiPart上传文件
        parameterHandlers = builder.parameterHandlers; //重要参数
      }
    
      static final class Builder {
        Builder(Retrofit retrofit, Method method) {
          this.retrofit = retrofit;
          this.method = method;
          this.methodAnnotations = method.getAnnotations();
          this.parameterTypes = method.getGenericParameterTypes();
          this.parameterAnnotationsArray = method.getParameterAnnotations();
        }
    
        RequestFactory build() {
          .....
          return new RequestFactory(this);
        }
      }
    }
    

    parameterHandlers则负责解析 API 定义时每个方法的参数,并在构造 HTTP 请求时设置参数;

    1. 调用子类HttpServiceMethod的HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory)方法,传入第一步得到的requestFactory, 所以loadServiceMethod的真正工作是交给HttpServiceMethod来完成的.

    3. HttpServiceMethod

    查看类的注释: 把接口方法转换为 HTTP请求. 真正的转换工作是在这里进行的.

    /** Adapts an invocation of an interface method into an HTTP call. */

    查看parseAnnotations方法

      static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
          Retrofit retrofit, Method method, RequestFactory requestFactory) {
        //1. 创建CallAdapter
        CallAdapter<ResponseT, ReturnT> callAdapter = createCallAdapter(retrofit, method);
        Type responseType = callAdapter.responseType();
        //设定的返回值类型不能是Retrofit和OKHttp内的Response.
        if (responseType == Response.class || responseType == okhttp3.Response.class) {
          throw methodError(method, "'"
              + Utils.getRawType(responseType).getName()
              + "' is not a valid response body type. Did you mean ResponseBody?");
        }
        //如果用Http的HEAD方法必须返回空
        if (requestFactory.httpMethod.equals("HEAD") && !Void.class.equals(responseType)) {
          throw methodError(method, "HEAD method must use Void as response type.");
        }
        //2. 创建responseConverter 
        Converter<ResponseBody, ResponseT> responseConverter =
            createResponseConverter(retrofit, method, responseType);
        //3. 创建callFactory 
        okhttp3.Call.Factory callFactory = retrofit.callFactory;
        return new HttpServiceMethod<>(requestFactory, callFactory, callAdapter, responseConverter);
      }
    
      private final RequestFactory requestFactory;
      private final okhttp3.Call.Factory callFactory;
      private final CallAdapter<ResponseT, ReturnT> callAdapter;
      private final Converter<ResponseBody, ResponseT> responseConverter;
    
      private HttpServiceMethod(RequestFactory requestFactory, okhttp3.Call.Factory callFactory,
          CallAdapter<ResponseT, ReturnT> callAdapter,
          Converter<ResponseBody, ResponseT> responseConverter) {
        this.requestFactory = requestFactory;
        this.callFactory = callFactory;
        this.callAdapter = callAdapter;
        this.responseConverter = responseConverter;
      }
    
    

    可以看到,这里获取了三个对象callAdapter, responseConverter, callFactory并保存为成员变量.

    1. callFactory 负责创建 HTTP 请求,HTTP 请求被抽象为了 okhttp3.Call 类,它表示一个已经准备好,可以随时执行的 HTTP 请求;
    2. callAdapter 把 retrofit2.Call<T> 转为 T(注意和 okhttp3.Call 区分开来,retrofit2.Call<T> 表示的是对一个 Retrofit 方法的调用),这个过程会发送一个 HTTP 请求,拿到服务器返回的数据(通过 okhttp3.Call 实现),并把数据转换为声明的 T 类型对象(通过 Converter<F, T> 实现);
    3. responseConverter 是 Converter<ResponseBody, T> 类型,负责把服务器返回的数据(JSON、XML、二进制或者其他格式,由 ResponseBody 封装)转化为 T 类型的对象;

    3.1 CallAdapter<ResponseT, ReturnT> callAdapter = createCallAdapter(retrofit, method);

    我们在构建Retrofit对象的时候会调用addCallAdapterFactory(RxJava2CallAdapterFactory.create()),这里用的是RxJava2CallAdapterFactory. 可以看到被添加到了内部的callAdapterFactories列表中

    public final class Retrofit {
      //Retrofit内部维护了一个CallAdapter.Factory列表
      private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
    
      public static final class Builder {
        private final Platform platform;
        private @Nullable okhttp3.Call.Factory callFactory;
        private @Nullable HttpUrl baseUrl;
        private final List<Converter.Factory> converterFactories = new ArrayList<>();
        private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
        private @Nullable Executor callbackExecutor;
        private boolean validateEagerly;
        
        // 我们指定的CallAdapter.Factory被添加到了列表中
        public Builder addCallAdapterFactory(CallAdapter.Factory factory) {
          callAdapterFactories.add(checkNotNull(factory, "factory == null"));
          return this;
        }
      }
    }
    

    查看CallAdapter<ResponseT, ReturnT> callAdapter = createCallAdapter(retrofit, method);方法

      private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT> createCallAdapter(
          Retrofit retrofit, Method method) {
        Type returnType = method.getGenericReturnType();
        Annotation[] annotations = method.getAnnotations();
        try {
          //noinspection unchecked
          //实际返回的是 retrofit.callAdapter(returnType, annotations);的结果
          return (CallAdapter<ResponseT, ReturnT>) retrofit.callAdapter(returnType, annotations);
        } catch (RuntimeException e) { // Wide exception range because factories are user code.
          throw methodError(method, e, "Unable to create call adapter for %s", returnType);
        }
      }
    

    查看retrofit.callAdapter(returnType, annotations);,调用了nextCallAdapter()方法.
    可以看到这里通过遍历callAdapterFactories列表, 根据返回类型returnType和注解annotations来找到对应的CallAdapter.Factory.
    举个例子: 如果返回值是Flowable或者Maybe,那么adapter肯定是RxJava2CallAdapterFactory而不是RxJavaCallAdapterFactory,因为这两个操作符在RxJava2中才被引入.

      public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
        return nextCallAdapter(null, returnType, annotations);
      }
    
      public CallAdapter<?, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
          Annotation[] annotations) {
        checkNotNull(returnType, "returnType == null");
        checkNotNull(annotations, "annotations == null");
    
        int start = callAdapterFactories.indexOf(skipPast) + 1;
        //遍历callAdapterFactories列表, 根据传入的returnType和annotations找到对应的CallAdapter.Factory, 这里也说明了一个Retrofit对象是支持多个CallAdapter.Factory的
        for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
          CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
          if (adapter != null) {
            return adapter;
          }
        }
       .....
      }
    

    3.2 okhttp3.Call.Factory callFactory = retrofit.callFactory;

    追踪retrofit.callFactory,发现在Retrofit对象build()的时候, 如果没有callFactory对象,就默认给一个callFactory = new OkHttpClient()
    当然了,Retrofit.Builder也是提供了allFactory(okhttp3.Call.Factory factory)方法供我们自定义

    public final class Retrofit {
      final okhttp3.Call.Factory callFactory;
    
      public static final class Builder {
        private @Nullable okhttp3.Call.Factory callFactory;
    
        Builder(Retrofit retrofit) {
          callFactory = retrofit.callFactory;
        }
    
        public Retrofit build() {
          okhttp3.Call.Factory callFactory = this.callFactory;
          if (callFactory == null) {
            //如果没有传入callFactory,默认给一个OkHttpClient
            callFactory = new OkHttpClient();
          }
       }
       
       //Retrofit也支持传入自定义的okhttp3.Call.Factory
       public Builder callFactory(okhttp3.Call.Factory factory) {
          this.callFactory = checkNotNull(factory, "factory == null");
          return this;
       }
    }
    

    3.3 Converter<ResponseBody, ResponseT> responseConverter = createResponseConverter(retrofit, method, responseType);

    和获取CallAdapter一样,调用的是Retrofit中的retrofit.responseBodyConverter方法

      Converter<ResponseBody, ResponseT> responseConverter =
            createResponseConverter(retrofit, method, responseType);
    
      private static <ResponseT> Converter<ResponseBody, ResponseT> createResponseConverter(
          Retrofit retrofit, Method method, Type responseType) {
        Annotation[] annotations = method.getAnnotations();
        try {
          //和获取CallAdapter一样,调用的是Retrofit中的方法
          return retrofit.responseBodyConverter(responseType, annotations);
        } catch (RuntimeException e) { // Wide exception range because factories are user code.
          throw methodError(method, e, "Unable to create converter for %s", responseType);
        }
      }
    

    查看retrofit.responseBodyConverter(responseType, annotations),逻辑和上面的retrofit.callAdapter(returnType, annotations)差不多,也是通过返回值和注解遍历Retrofit中的converterFactories列表查找合适的convertFactory

      public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) {
        return nextResponseBodyConverter(null, type, annotations);
      }
    
      public <T> Converter<ResponseBody, T> nextResponseBodyConverter(
          @Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) {
        checkNotNull(type, "type == null");
        checkNotNull(annotations, "annotations == null");
    
        int start = converterFactories.indexOf(skipPast) + 1;
        for (int i = start, count = converterFactories.size(); i < count; i++) {
          Converter<ResponseBody, ?> converter =
              converterFactories.get(i).responseBodyConverter(type, annotations, this);
          if (converter != null) {
            //noinspection unchecked
            return (Converter<ResponseBody, T>) converter;
          }
        }
      }
    

    3.4 invoke(args != null ? args : emptyArgs)

      @Override ReturnT invoke(Object[] args) {
        //真正发起HTTP call的流程,后面分析
        return callAdapter.adapt(
            new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
      }
    

    requestFactory是父类ServiceMethod的包含了请求头,方法名,url等等信息.
    CallAdapter,callFactory,responseConverter在Retrofit创建的时候就提供了,在前面三步做的只是根据返回值和注解查找的过程.

    他们分别由okhttp3.Call.FactoryCallAdapter.FactoryConverter.Factory三个工厂提供. 工厂模块之间互不影响; 每个模块通过实现工厂接口也隐蔽了创建的细节.符合高内聚低耦合的标准

    这些参数都是为了callAdapter.adapt( new OkHttpCall<>(requestFactory, args, callFactory, responseConverter))这一步发起HTTP call, 后面分析CallAdapter的时候会解释.

    4. 模块的实现

    4.1 CallAdapter.Factory

    Retrofit内置了DefaultCallAdapterFactoryExecutorCallAdapterFactory两个实现.前者什么也不做,后者会将任务分发到Retforit.Builder().XXX...build()时传入的callbackExecutor来执行.

    class Platform {
      List<? extends CallAdapter.Factory> defaultCallAdapterFactories(
          @Nullable Executor callbackExecutor) {
        if (callbackExecutor != null) {  //如果指定了Executor,就交给他调度
          return singletonList(new ExecutorCallAdapterFactory(callbackExecutor));
        }   
        //默认的
        return singletonList(DefaultCallAdapterFactory.INSTANCE);
      }
    }
    

    以上两种的返回值都是retrofit2.Call.
    通常Retrofit都是配合RxJava来使用的, 这时候我们用到了RxJava2CallAdapter来把retrofit2.Call转换为我们熟悉的Flowable,Observable等对象.

    RxJavaCallAdapterFactory#get 方法中对返回值的类型进行了检查

    if (rawType == Completable.class) {
      // Completable is not parameterized (which is what the rest of this method deals with) so it
      // can only be created with a single configuration.
      return new RxJava2CallAdapter(Void.class, scheduler, isAsync, false, true, false, false,
          false, true);
    }
    
    if (rawType != Observable.class && !isFlowable && !isSingle && !isMaybe) {
       return null;
    }
    .... 
    return new RxJava2CallAdapter(responseType, scheduler, isAsync, isResult, isBody, isFlowable,
            isSingle, isMaybe, false);
    

    构造RxJava2CallAdapter对象

      RxJava2CallAdapter(Type responseType, @Nullable Scheduler scheduler, boolean isAsync,
          boolean isResult, boolean isBody, boolean isFlowable, boolean isSingle, boolean isMaybe,
          boolean isCompletable) {
        this.responseType = responseType;
        this.scheduler = scheduler;
        this.isAsync = isAsync;
        this.isResult = isResult;
        this.isBody = isBody;
        this.isFlowable = isFlowable;
        this.isSingle = isSingle;
        this.isMaybe = isMaybe;
        this.isCompletable = isCompletable;
      }
    

    上面提到过HttpServiceMethod#invoke调用了callAdapter#adapt方法,我们关注下

    @Override public Object adapt(Call<R> call) {
      // 这一步把我们原来的 Call 转换成了 Observable 对象
      Observable<Response<R>> responseObservable = isAsync
          ? new CallEnqueueObservable<>(call)  //加入队列
          : new CallExecuteObservable<>(call);   //马上执行
      Observable<?> observable;
      if (isResult) {
        observable = new ResultObservable<>(responseObservable);
      } else if (isBody) {
        observable = new BodyObservable<>(responseObservable);
      } else {
        observable = responseObservable;
      }
      //省略了Single,Flowable背压,Maybe等等处理
       .....
      return RxJavaPlugins.onAssembly(observable);
    }
    

    new CallEnqueueObservable<>(call)为例, 把传入的 retrofit2.Call 保存为originalCall

    final class CallEnqueueObservable<T> extends Observable<Response<T>> {
      private final Call<T> originalCall;
    
      CallEnqueueObservable(Call<T> originalCall) {
        this.originalCall = originalCall;
      }
      
      //Observable定义的抽象方法,在Observable.subscribe()的时候会被调用
      @Override protected void subscribeActual(Observer<? super Response<T>> observer) {
        // Since Call is a one-shot type, clone it for each new observer.
        Call<T> call = originalCall.clone();
        CallCallback<T> callback = new CallCallback<>(call, observer);
        observer.onSubscribe(callback);
        if (!callback.isDisposed()) {
          call.enqueue(callback);
        }
      }
    }
    

    这里 retrofit2.Call 接口的实现是 OkHttpCall, 查看OkHttpCall#enqueue
    ,这里面也有一句call.enqueue,这里的call 是 okhttp3.Call,到这里,才是真正的把请求加入OkHttp的请求队列

    final class OkHttpCall<T> implements Call<T> {
      @Override public void enqueue(final Callback<T> callback) {
        checkNotNull(callback, "callback == null");
    
        okhttp3.Call call;
        Throwable failure;
        //注意了,这里的call是okhttp3.Call对象
        call = rawCall = createRawCall();
    
         //这里用锁和executed 变量 控制线程竞争
        synchronized (this) {
          if (executed) throw new IllegalStateException("Already executed.");
          executed = true;
          ....
        //okhttp3.Call.enqueue,加入OkHttp的请求队列
        call.enqueue(new okhttp3.Callback() {
          @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
            Response<T> response;
            try {
              response = parseResponse(rawResponse);
            } catch (Throwable e) {
              throwIfFatal(e);
              callFailure(e);
              return;
            }
    
            try {
              callback.onResponse(OkHttpCall.this, response); //成功响应
            } catch (Throwable t) {
              t.printStackTrace();
            }
          }
    
          @Override public void onFailure(okhttp3.Call call, IOException e) {
            callFailure(e);
          }
    
          private void callFailure(Throwable e) {
            try {
              callback.onFailure(OkHttpCall.this, e); //失败的回调
            } catch (Throwable t) {
              t.printStackTrace();
            }
          }
        });
      }
    }
    

    在Okhttp请求成功失败时,CallEnqueueObservable.CallCallback调用了Observable.onNext(), onComplete(), onError()方法.

    final class CallEnqueueObservable<T> extends Observable<Response<T>>
      private static final class CallCallback<T> implements Disposable, Callback<T>
        @Override public void onResponse(Call<T> call, Response<T> response) {
          if (disposed) return;
    
          try {
            observer.onNext(response);
    
            if (!disposed) {
              terminated = true;
              observer.onComplete();
            }
          } catch (Throwable t) {
            if (terminated) {
              RxJavaPlugins.onError(t);
            } else if (!disposed) {
              try {
                observer.onError(t);
              } catch (Throwable inner) {
                Exceptions.throwIfFatal(inner);
                RxJavaPlugins.onError(new CompositeException(t, inner));
              }
            }
          }
        }
    
        @Override public void onFailure(Call<T> call, Throwable t) {
          if (call.isCanceled()) return;
    
          try {
            observer.onError(t);
          } catch (Throwable inner) {
            Exceptions.throwIfFatal(inner);
            RxJavaPlugins.onError(new CompositeException(t, inner));
          }
        }
      }
    }
    

    这里有一段伪代码

    Retrofit.Builder()
            .baseUrl(NetWorkConstant.PORT_URL)
            .client(getHttpClient(COMMON_HEAD))
             //RxJava2CallAdapterFactory把retrofit2.Call 转换成我们想要的Observable等RxJava里的对象
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
            .create(ApiService::class.java)
            .login(params) //login方法执行完后,会发起okhttp3.Call.enqueue
            .subscribe({
                println("onNext")  //okhttp3.Callback的回调里会调用Observable.onNext, onError, onComplete
            },{
                println("onError")
            },{
                print("onComplete")
            })
    

    4.2 okhttp3.Call.Factory

    顾名思义,我们发起请求 okhttp3.Call call对象就是由他创建的.主要分为三个步骤.

    final class OkHttpCall<T> implements retrofit2.Call<T> {
      private okhttp3.Call createRawCall() throws IOException {
        //调用okhttp3.Call.Factory创建okhttp3.Call
        okhttp3.Call call = callFactory.newCall(requestFactory.create(args));
        if (call == null) {
          throw new NullPointerException("Call.Factory returned null.");
        }
        return call;
      }
    }
    
    //OkHttpClient实现了Call.Factory, 在newCallI()的实现里调用了RealCall.newRealCall()
    public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory {
      @Override public Call newCall(Request request) {
        return RealCall.newRealCall(this, request, false /* for web socket */);
      }
    }
    
    //真正创建了okhttp3.Call
    final class RealCall implements Call
      static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) {
        // Safely publish the Call instance to the EventListener.
        RealCall call = new RealCall(client, originalRequest, forWebSocket);
        call.eventListener = client.eventListenerFactory().create(call);
        return call;
      }
    }
    

    4.3 Converter.Factory

    这里还是讨论常用的 GsonConverterFactory ,和 CallAdapterFactory 一样,实现接口就可以进行自定义. 以GsonConverterFactory为例

    .addConverterFactory(GsonConverterFactory.create(gson))
    

    创建 GsonConverterFactory

    public final class GsonConverterFactory extends Converter.Factory {
      public static GsonConverterFactory create() {
        return create(new Gson());
      }
    
      public static GsonConverterFactory create(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        return new GsonConverterFactory(gson);
      }
    
      private final Gson gson;
    
      private GsonConverterFactory(Gson gson) {
        this.gson = gson;
      }
    }
    

    在invoke方法时,通过returnType, annotations找到合适的 Converter

      //上面已经提到了, HttpServiceMethod里会调用这一句
      public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) {
        return nextResponseBodyConverter(null, type, annotations);
      }
    
      public <T> Converter<ResponseBody, T> nextResponseBodyConverter(
          @Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) {
        //遍历寻找Converter
        int start = converterFactories.indexOf(skipPast) + 1;
        for (int i = start, count = converterFactories.size(); i < count; i++) {
          Converter<ResponseBody, ?> converter =
              //调用Converter. responseBodyConverter()方法
              converterFactories.get(i).responseBodyConverter(type, annotations, this);
          if (converter != null) {
            //noinspection unchecked
            return (Converter<ResponseBody, T>) converter;
          }
        }
      }
    

    调用GsonConverterFactory 创建 GsonResponseBodyConverter对象

    public final class GsonConverterFactory extends Converter.Factory {
      @Override
      public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
          Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        //创建了GsonResponseBodyConverter对象
        return new GsonResponseBodyConverter<>(gson, adapter);
      }
    }
    
    
    final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
      private final Gson gson;
      private final TypeAdapter<T> adapter;
    
      GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
      }
      
      //接口里的convert 方法, 帮我们把value转换为我们想要的格式
      @Override public T convert(ResponseBody value) throws IOException {
        JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try {
          T result = adapter.read(jsonReader);
          if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
            throw new JsonIOException("JSON document was not fully consumed.");
          }
          return result;
        } finally {
          value.close();
        }
      }
    }
    

    真正帮我们完成数据转json操作的是 GsonResponseBodyConverter.convert(ResponseBody value)方法,那么他在什么时候被调用呢?
    在 okhttp3.Call 的onResponse()里, 会把okhttp3.Response解析成json

    call.enqueue(new okhttp3.Callback() {
          @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
            Response<T> response;
            try {
              response = parseResponse(rawResponse);
            } catch (Throwable e) {
              throwIfFatal(e);
              callFailure(e);
              return;
            }
    }
    

    感谢

    拆轮子系列:拆 Retrofit

    相关文章

      网友评论

          本文标题:Retrofit2.5.0解析

          本文链接:https://www.haomeiwen.com/subject/judyzqtx.html