Java教程

retrofit2源码阅读

本文主要是介绍retrofit2源码阅读,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.retrofit.create 创建retrofit

2.loadServiceMethod(method).invoke(args) 动态代理method,并在repos.enqueue 中调用invoke

3.ServiceMethod.parseAnnotations(this, method)

4.RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method); 解析注解,生成requestFactory

5.HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory) 生成HttpServiceMethod 方法,初始化

RequestFactory requestFactory,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT>responseConverter) {
this.requestFactory = requestFactory;
this.callFactory = callFactory;
this.responseConverter = responseConverter;

6.HttpServiceMethod 的invoke 为

@Override
  final @Nullable ReturnT invoke(Object[] args) {
    Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
    return adapt(call, args);
  }

     @Override
    protected ReturnT adapt(Call<ResponseT> call, Object[] args) {
      return callAdapter.adapt(call);
    }

现在开始追callAdapter

return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
CallAdapter<ResponseT, ReturnT>callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);

private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT> createCallAdapter(
      Retrofit retrofit, Method method, Type returnType, Annotation[] annotations) {
    try {
      //noinspection unchecked
      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);
    }
  }

CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);

现在开始追callAdapterFactories的get方法

List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
      callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));

return new CallAdapter<Object, Call<?>>() {
      @Override
      public Type responseType() {
        return responseType;
      }

      @Override
      public Call<Object> adapt(Call<Object> call) {
        return executor == null ? call : new ExecutorCallbackCall<>(executor, call);
      }
    };

实际上  adapt调用的是   ExecutorCallbackCall<>(executor, call) 方法

ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
      this.callbackExecutor = callbackExecutor;
      this.delegate = delegate;
    }

初始化了一个call

retrofit.create(GitHubService::class.java) 整个代码 就是初始化了一个ExecutorCallbackCall
service.listRepos 是获取接口上初始上的方法  
repos.enqueue 实际上也就是调用 ExecutorCallbackCall里面的enqueue,

 this.delegate = delegate;  这个delegate是invoke的第一行传入的OkHttpCall

@Override
    public void enqueue(final Callback<T> callback) {
      Objects.requireNonNull(callback, "callback == null");

      delegate.enqueue(
          new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, final Response<T> response) {
              callbackExecutor.execute(
                  () -> {
                    if (delegate.isCanceled()) {
                      // Emulate OkHttp's behavior of throwing/delivering an IOException on
                      // cancellation.
                      callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
                    } else {
                      callback.onResponse(ExecutorCallbackCall.this, response);
                    }
                  });
            }

            @Override
            public void onFailure(Call<T> call, final Throwable t) {
              callbackExecutor.execute(() -> callback.onFailure(ExecutorCallbackCall.this, t));
            }
          });

总结:retrofit2通过动态代理 + 注解取出关键信息,初始化接口里面的方法,初始化方法后用invoke,生成okhttpcall 调用 apat 初始化 试配器的calll

通过包装okhttp call实现enqueue ,将okhttp call装饰者模式包装了一层call,使用excute+handle

实现线程切换,回调接口

val retrofit = Retrofit.Builder()
            .baseUrl("https://api.github.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val service = retrofit.create(GitHubService::class.java)
        val repos: Call<List<Repo>> = service.listRepos("octocat")
        repos.enqueue(object:Callback<List<Repo>> {
            override fun onResponse(call: Call<List<Repo>>, response: Response<List<Repo>>) {

            }

            override fun onFailure(call: Call<List<Repo>>, t: Throwable) {

            }
        })
这篇关于retrofit2源码阅读的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!