0

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?

Synth
  • 21
  • 1
  • 4

1 Answers1

0

I think if GsonConverterFactory is only needed for Retrofit instance and this retrofit instance is singleton then the way it's created in your code is fine, but if the retrofit instance is scoped to another scope like activity for example then each time an activity is created a new retrofit instance will be created therefore new GsonConverterFactory instance will be created so to avoid this, provide GsonConverterFactory as a hilt dependency.

AT Amrani
  • 228
  • 1
  • 8
  • After working with Hilt more I think I understand your answer now. But to clarify, if the Retrofit instance is scoped to an activity, would you scope the GsonConverterFactory provider as a singleton or scoped to activity too? I assume doing the latter would be pointless since the GsonConverterFactory would be recreated each time the Retrofit instance is provided, right? – Synth Aug 10 '23 at 19:36