Note: This article is based on Retrofit version 2.0 and is analyzed with RxJava.

Com. Squareup. Retrofit2: retrofit: 2.0.0

Com. Squareup. Retrofit2: converter – gson: 2.0.0

Com. Squareup. Retrofit2: adapter – rxjava: 2.0.0

​ Retrofit adapts a Java interface to HTTP calls by using annotations on the declared methods to how requests are made.

This article analyzes Retrofit’s collaboration with RxJava to gain an in-depth understanding of how Retrofit works and to answer questions in my mind.

confusion

  1. How do we send the request after we call the interface’s methods? What’s going on behind this?
  2. How did Retrofit and OkHttp work together?
  3. What exactly happens to the data in Retrofit? How does it return rxJava.Observable?

Retrofit.create method analysis

Retrofit’s Create method, as the entry point for Retrofit, is of course the first to be analyzed.

  public <T> T create(final Class<T> service) {
    //Verify that the interface is reasonable
    Utils.validateServiceInterface(service);
    //The default false
    if (validateEagerly) {
      eagerlyValidateMethods(service);
    }
    //A dynamic proxy
    return (T) Proxy.newProxyInstance(service.getClassLoader(), newClass<? >[] { service },new InvocationHandler() {
          //Platform abstraction, specify the default CallbackExecutor CallAdapterFactory, Android platform is Android (Java8 iOS we don't care)
          private final Platform platform = Platform.get();
          //This is where all the method calls in ApiService go
          @Override public Object invoke(Object proxy.Method method.Object.args)
              throws Throwable {
            // If the method is a method from Object then defer to normal invocation.
            //The comment already indicates that Object methods do not matter
            if (method.getDeclaringClass() = = Object.class) {
              return method.invoke(this, args);
            }
            //Java8 default method, Android does not support the default method, so do not need to manage for the time being
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            //Focus on the latter analysis
            //Generate a ServiceMethod for Method
            ServiceMethod serviceMethod = loadServiceMethod(method);
            //Wrap it as OkHttpCall
            OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);      //request
            return serviceMethod.callAdapter.adapt(okHttpCall); }}); }Copy the code

As you can see in the code above, Retrofit’s main principle is to leverage Java’s dynamic proxy technology, The ApiService method calls on InvocationHandler. Invoke, and then build the ServiceMethod, OKHttpCall, return callAdapter. Adapt the results.

To find out, you need to analyze those last three lines of code.

One step at a time.

OkHttpCall

OkHttpCall = new OkHttpCall<>(serviceMethod, args); An OkHttpCall is generated for ServiceMethod and args(parameters).

As you might guess from the name, OkHttpCall is a combination wrapper around okHttp3.Call, which it is. OkHttpCall has a member okhttp3.Call rawCall.

Process analysis flowchart summary

The overall flow chart is as follows:

Answer questions

We can answer the question before.

Second question: How did Retrofit and OkHttp work together?

In Retrofit, ServiceMethod takes all the parameters of an Http request, OkHttpCall is wrapped as a combination of okHttp3. call, and the two work together. Generate the Request and okHttp3.call required by OkHttp and hand it to OkHttp to send the Request. (Call.execute () is used in this context)

Retrofit encapsulates OkHttp and adds functionality and extensions that reduce development costs.

summary

The source code for Retrofit is actually very easy to follow and understand, unlike looking at the framework code and then disappearing.

Retrofit’s code is really beautiful, and it’s a great way to use design patterns.