Christophe Beyls
1 min readJun 16, 2019

--

This is really out of scope of the article but here is a quick review:

Well it looks like you don’t need a singleton with argument at all, since you want to create a new AppAPI instance every time the config changes. Also, your ApiController2 class probably leaks an activity because it keeps a reference to Context.

You can still make the OkHttpClient a singleton. In your example, since it doesn’t need any Context to be built, you can simply use a property inside an object. Here’s the idea:

object ApiFactory {
private val okHttpClient = OkHttpClient.Builder()
.dispatcher(Dispatcher())
.connectionPool(ConnectionPool())
.build()

fun
buildAPI(context: Context): AppAPI {
val baseUrl = loadBaseUrlFromConfig(context)

return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.baseUrl(baseUrl)
.build()
.create(AppAPI::class.java)
}
}

Then once you build the AppAPI object you should keep it around in a var somewhere in order to not rebuild it for each HTTP request. But it’s definitely not a singleton since you may have to replace it with a different instance later.

--

--

Christophe Beyls
Christophe Beyls

Written by Christophe Beyls

Android developer from Belgium, blogging about advanced programming topics.

No responses yet