1

My application can connect to several customers' base stations (servers), which each have their own baseUrl and certificate, on their local network. The app can only connect with a single one at a time, and the user can select a server through the Settings. To set the baseUrl dynamically without re-creating the Retrofit instance, I implemented an interceptor on the OkHttpClient. But changing certificate/SSLContext for an existing OkHttpClient / Retrofit provided by Hilt seems impossible without recreating a new Retrofit object with a new OkHttpClient.

I am considering using this user's second solution, which involves recreating Retrofit instances and providing them with Hilt through a RetrofitHolder wrapper class:

public class RetrofitHolder {
   Retrofit retrofit;

   //getter, setter
}

But I'd rather not recreate the Retrofit instances if possible. Any idea how?

Synth
  • 21
  • 1
  • 4
  • 1
    Creating a new `Retrofit` instance, whether from scratch or using `newBuilder()`, will be your simplest solution. `Retrofit` instances are immutable by design. You're welcome to try to play some games and try to have an `SSLContext` that uses an `SSLContextSpi` that itself proxies to the *real* `SSLContextSpi` tied to your base station, so you can swap `SSLContextSpi` implementations on the fly. I don't know how well that would work, and I do not know how reliable the result would be. Personally, I would need a *really* good reason to go down that rabbit hole again. – CommonsWare Jul 21 '23 at 23:27
  • Ah, I see. It seems it might be more work and complexity than it's worth. Do you know if there is a better or easier way to recreate a Retrofit instance that is being provided by a Hilt @Provides method, other than the RetrofitHolder mentioned above? – Synth Jul 22 '23 at 08:22
  • 1
    Depending on your setup, [using Dagger/Hilt scopes](https://dagger.dev/hilt/components.html) might help. If you wind up with a different scope (say, a different activity instance) when you switch base stations, you should be able to avoid the holder. Objects in the new scope would get a fresh injection of the `Retrofit` instance, so you only need it to be set up for that new base station. – CommonsWare Jul 22 '23 at 11:03

0 Answers0