The application is a client for an information system designed for a large number of organizations (more than 2000). Each organization uses its own URL of the form:

  • subdomain1.domain.com
  • subdomain2.domain.com
  • subdomain3.domain.com

The file structure of all is identical.

For example:

@GET ("login") @GET ("notice") @GET ("events"), etc.

How, using the combination of Retrofit & Dagger2, to dynamically change the baseUrl?

    1 answer 1

    To dynamically change the baseUrl to Retrofit, you need to pass into it not a hard-coded url, but the implementation of the BaseUrl interface BaseUrl

     public class UrlProvider implements BaseUrl { private HttpUrl httpUrl; public UrlProvider(String url) { //передаем стандартный урл httpUrl = HttpUrl.parse(url); } // вызываем когда необходимо изменить урл public void changeUrl(@NonNull String url) { httpUrl = HttpUrl.parse(url); } @Override public HttpUrl url() { return httpUrl; } } 

    Well, in the module for Daggera do something like this

     @Provides @Singleton UrlProvider urlProvider(PrefWrapper prefWrapper){ return new UrlProvider(prefWrapper.getPref().url()); } @Provides @Singleton Retrofit provideRetrofit(UrlProvider urlProvider){ return new Retrofit.Builder() //прочие настройки .baseUrl(urlProvider) .build(); } 

    If you need to change the url, simply request the UrlProvider dependency from UrlProvider , and set its new URL

    PrefWrapper in this case is a wrapper around the SharedPreference which stores the current URL. You can use something of your own.

    • I'm just starting to work with DI and I clearly lack understanding of the basics. Thank you so much for the detailed response! - Artemii Glukhov