How Retrofit works under the hood

Viewed 1401

Question regarding Retrofit2:

After you build a Retrofit instance you then call one of the interface (client) methods to "send a request"

For example if you have an interface like this:

@POST("webhook.php")
Call<String>  queueCustomer(@Body String queue);

and a Retrofit instance of "client" that you created with the create method, and then you call it like this:

client.queueCustomer(someString)

I'm assuming this is actually making the network request. However, you take the Call object returned from this and call something like:

callObject.enqueue(........)

Are you making a follow up network request when you call enqueue? Is this two network requests or is the first part: client.queueCustomer(someString) just constructing the object that will be send via callObject.enqueue(........)?

Thanks in advance

1 Answers

When you setup the retrofit instance and create service with Retrofit.create(ApiService::class.java), then service interface implementation created with proxy classes. Below is code block from Retrofit class which constructs service interface implementation and call objects. Actually retrofit is a wrapper library to turn interfaces in to OkHttp calls. So when you call interface method it just return you to corresponding call object but unless you run enqueue or execute method it will not make a request.

public <T> T create(final Class<T> service) {
    validateServiceInterface(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 @Nullable Object invoke(Object proxy, Method method,
              @Nullable Object[] args) throws Throwable {
            // If the method is a method from Object then defer to normal invocation.
            if (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
          }
        });
  }
Related