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 ) {
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With