Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create multiple retrofit base url in dagger hilt and inject them

I am new in dagger hilt I am using @Named annotation to make unique but I have no idea how to use. I want to create multiple retrofit base Url object and inject here is my code

@Singleton
@Provides
@LiveUrl
fun provideRetrofitInstance(
    okHttpClient: OkHttpClient,
    gsonConverterFactory: GsonConverterFactory): Retrofit {
    return Retrofit.Builder()
        .baseUrl(LIVE_SERVER)
        .client(okHttpClient)
        .addConverterFactory(gsonConverterFactory)
        .build()
}
enter code here

@Singleton
@Provides
@BlogUrl
fun provideRetrofit2Instance(
    okHttpClient: OkHttpClient,
    gsonConverterFactory: GsonConverterFactory): Retrofit {
    return Retrofit.Builder()
        .baseUrl(LIVE_BLOGSERVER)
        .client(okHttpClient)
        .addConverterFactory(gsonConverterFactory)
        .build()
}

class RemoteDataSource @Inject constructor( private val liveApiInterface: NewApiInterface ) {

}

like image 212
Kanhiya Bisht Avatar asked Jan 19 '26 19:01

Kanhiya Bisht


1 Answers

If you want to have multiple Retrofit APIs with different urls, you could also consider using Assisted Injection:

@AssistedFactory
interface RetrofitFactory {
    fun create(baseUrl: String): RetrofitBuilder
}

class RetrofitBuilder @AssistedInject constructor(
    @Assisted val baseUrl: String,
    val okHttpClient: OkHttpClient
) {
    inline fun <reified T> build(): T {
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(...)
            .client(okHttpClient)
            .build()
            .create()
    }
}

This can then be used like:

@Provides
fun provideLiveApi(retrofitFactory: RetrofitFactory): LiveApi =
    retrofitFactory.create(API_BASE_URL).build()
like image 123
Wrakor Avatar answered Jan 22 '26 20:01

Wrakor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!