Is there a better way to provide Retrofit/OkHttpCl...
# dagger
a
Is there a better way to provide Retrofit/OkHttpClient instances with different timeouts using Dagger Hilt than duplicating everything? More in 🧵
I have a project that calls multiple API calls using Retrofit. Most of the calls should use a timeout of 10 seconds, which is plenty enough. However there's a few calls where the backend server has to calculate before sending a response back, which can take more than 10 seconds. The current DI module is written like this:
Copy code
@Provides
fun provideOkHttpClient(): OkHttpClient {
    return OkHttpClient.Builder()
        .connectTimeout(Duration.ofSeconds(DEFAULT_TIMEOUT_SECONDS))
        .readTimeout(Duration.ofSeconds(DEFAULT_TIMEOUT_SECONDS))
        .build()
}

@Provides
@Singleton
fun provideRetrofit(
    client: OkHttpClient,
    moshi: Moshi,
): Retrofit = Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(
        MoshiConverterFactory.create(moshi)
    )
    .client(client)
    .build()

@Provides
@Singleton
fun provideMyApi(
    retrofit: Retrofit,
): MyApi {
    return retrofit.create()
}

@Provides
@Singleton
fun provideMyLongApi(
    retrofit: Retrofit, // OkHttp client should have longer timout
): MyLongApi {
    return retrofit.create()
}
t
You could create a custom interceptor, and use an annotation to mark certain requests as having a specific timeout. The interceptor would then manage the timeout per request
Otherwise you might just need to maintain two separate retrofit instances as you've proposed
a
Could you provide some sample code for the interceptor solution? I don't really understand how that works.
t
Something along these lines perhaps? It's not something I've done myself https://chat.openai.com/share/22bdd37d-47ec-4b44-8058-353b34c95799
❤️ 1
a
Thanks I think this will work
t
I would maybe question the need to have different timeouts for different requests. 10 seconds is a long time.. as is the default(?) of 30 seconds.. Would it hurt to just use a longer time that suits all cases?
a
I'm still experimenting, but in the end it will probably be like a 5 to 30+ seconds difference. So this helped a lot.
t
In that case, I would just set the timeout to 30s for all requests
But do whatever suits your needs 🙂