1

I'm using dagger hilt as a dependency injection framework in my project, however, I have this situation where I need to provide Retrofit instance. Normally I do it using the @Provides annotation.

    @Provides
    @Singleton
    fun provideRetrofit(
        okHttpClient: OkHttpClient,
        scalarsConverterFactory: ScalarsConverterFactory,
    ): Retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(scalarsConverterFactory)
        .client(okHttpClient)
        .build()

But now I came to a situation where I need to have a dynamic BASE_URL. In normal cases when the class is created by me, I use the @AssestedFactory and @AssestedInject annotations.

How to use the @AssestedFactory to provide a dynamic BASE_URL in my situation.

Hamza Sharaf
  • 811
  • 9
  • 25
  • Create a retrofit factory class, and a create method which takes in the dynamic url and builds the retrofit instance when needed? – Chris Aug 11 '21 at 10:47
  • How dynamic do you need it? Is it sufficient to bind a `@BaseUrl String` (using a qualifier you create) into the dependency graph and then pass it as a `@Provides` function parameter? Or do you need to be able to change the BASE_URL during the lifetime of the app, which suggests that the Retrofit instance shouldn't be as `@Singleton` as it appears in your posted code? – Jeff Bowman Aug 12 '21 at 21:56
  • @JeffBowman What I mean is that the `BASE_URL` can be changed during the runtime. Considering your point of changing the `@Singleton` to another scope. How can I inject the `BASE_URL` into the retrofit instance? – Hamza Sharaf Aug 13 '21 at 08:19
  • Per https://github.com/square/retrofit/issues/1404#issuecomment-207408548 this isn't possible in Retrofit 2; you'll need to follow the instructions at [this similar question](https://stackoverflow.com/q/36498131/1426891). Suggesting this as a dupe. – Jeff Bowman Aug 13 '21 at 14:21
  • Does this answer your question? [Set dynamic base url using Retrofit 2.0 and Dagger 2](https://stackoverflow.com/questions/36498131/set-dynamic-base-url-using-retrofit-2-0-and-dagger-2) – Jeff Bowman Aug 13 '21 at 14:21

0 Answers0