chanakya m
chanakya m

Reputation: 1

Why do we need to create a network service class as singleton in Android?

I am researching how to create a network service class using retrofit for making api calls, then I found almost all the examples I found were suggesting me to create a network service class as singleton as follows:

object ServiceGenerator{

    val builder = Retrofit.Builder()
                          .baseUrl("url")
                          .addConverterFactory(
                          GsonConverterFactory.create());

    val retrofit = builder.build();

    val httpClient = OkHttpClient.Builder();

    fun <T> createService(serviceClass:<T>):T {
               return retrofit.create(serviceClass);
        }         

    }

Any reason to create a network singleton class as singleton? what would happen if we create a new instance every time we make an api call ?

If any one can help me under this ?

Upvotes: 0

Views: 266

Answers (1)

Egor
Egor

Reputation: 40218

The reason is that Retrofit.create() uses a reflective Proxy.newProxyInstance call under the hood (source) to create and instantiate a proxy class implementing the service interface, and reflection has historically been slow on Android devices. The instance can be safely cached, so recreating it on every API call will just result in slower networking.

Upvotes: 1

Related Questions