I've been learning dependency injection with Hilt, and for some things it is obvious that you need to provide a dependency for another dependency, for example when providing a custom okHttpClient
with certificate and hostname verification to a Retrofit provider:
@Singleton
@Provides
fun provideOkHttpClient(otherDependencies: Dependency): OkHttpClient {
return OkHttpClient.Builder()
...
.build()
}
@Singleton
@Provides
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl("https://1.2.3.4")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
}
However, as you noticed, the .addConverterFactory()
has a GsonConverterFactory.create()
provided by an Import directly instead of an @Provides
function, and I noticed this in several guides online. Yet, a person on Stackoverflow recommended you provide it as a Hilt dependency:
Clean your @Singleton module, so that it provides GsonConverterFactory, and RxJavaCallAdapterFactory to make proper use of dagger and not recreate shared objects.
I think the key is the last sentence, to "not recreate shared objects". But if I only need it once for one Retrofit provider, do I even need to make an @Provides provideGsonConverterFactory()
function, or is providing .addConverterFactory(GsonConverterFactory.create())
directly fine?