I'm learning about retrofit interceptors, for work purposes I'm using dagger-hilt for the injection of dependencies to fragments etc. I wrote a custom interceptor to check for connection errors and I'm trying to add it to the Retrofit.Builder()
:
@Provides
@Singleton
fun provideApi(): StoreApi {
return Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build()
.create(StoreApi::class.java)
}
however, I have no clue how to pass that:
val okHttpClient = OkHttpClient()
.newBuilder()
.addInterceptor(ConnectivityInterceptor)
.build()
as a .client() to the retofit builder (even with dagger-hilt), any ideas?
CodePudding user response:
You can setup a module something like this where you provide all the dependency requirements as functions and exposing them to dagger through @Provides
then leave dagger to provide the dependencies as function arguments to build the dependency graph :
@Module class ApiModule {
@Provides
@Singleton
internal fun provideApi(retrofit: Retrofit): FakeStoreApi {
return retrofit
.create(StoreApi::class.java)
}
@Provides
@Singleton
internal fun retrofit(client: OkHttpClient): Retrofit =
Retrofit.Builder()
.client(client)
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build()
@Provides
@Singleton
internal fun client(connectivityInterceptor: ConnectivityInterceptor): OkHttpClient =
OkHttpClient.Builder()
.addInterceptor(connectivityInterceptor)
.build()
@Provides
@Singleton
internal fun interceptor(): ConnectivityInterceptor = ConnectivityInterceptor()
}
This is a trivial example based on the supplied code. Also new
is not a valid kotlin keyword. Also I assume FakeStoreApi
is an interface and parent to StoreApi
? Seems the wrong way round, but going based on supplied code..