Retrofit How To Change Base URL

  android, dagger-2, dagger-hilt, retrofit, retrofit2

I know that Retrofit has @URL capability, but is there another solution to dynamically set base url on retrofit instance? I am using Retrofit + Dagger by the way

For example I want to have a fragment to change the base url of my application

MY Retrofit Instance

@Module
@InstallIn(SingletonComponent::class)
object RetrofitInstance {

    var appCtx = Sugar.applicationContext()

    var client = OkHttpClient.Builder().addInterceptor(ConnectivityInterceptor(appCtx.applicationContext)).build()
    
    @Provides
    @Singleton
    fun provideRetrofit(): Retrofit =
        Retrofit.Builder()
            .baseUrl(BuildConfig.URL_BASE)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()

    @Provides
    @Singleton
    fun provideApi(retrofit: Retrofit): IApi =
        retrofit.create(IApi::class.java)


}

Source: Android Questions

LEAVE A COMMENT