How to change Retrofit baseUrl from shared preferences at runtime

Viewed 777

I am trying to change the Retrofit baseUrl from SharedPreferences in my app at runtime, but the change is only implemented when I close and open the app. I have tried using onSharedPreferenceChangeListener() and onPreferenceChangeListener() but I still get the same result. How do I implement the listeners so that they change the baseUrl at runtime?

    private val moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()

    private val retrofit = Retrofit.Builder()
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .baseUrl(CompanyApiService .apiBaseUrl)
        .build()

    interface CompanyApiService {
        @GET("employees")
        fun getEmployeesAsync(): Deferred<List<Employees>>

        @GET("title/{id}")
        fun getTitlesAsync(@Path("id") id: Int): Deferred<List<Titles>>

        @POST("message")
        fun submitMessage(@Body message: Message): Call<String>
    }

    object CompanyApi {
        val retrofitService: CompanyApiService by lazy {
        retrofit.create(CompanyApiService ::class.java)
    }

    var apiBaseUrl = ""
    }

MainActivity.kt

    class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {

    ...

        PreferenceManager.setDefaultValues(this, R.xml.main_preference, false)
        val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this)
        sharedPrefs.registerOnSharedPreferenceChangeListener(this)

        val apiBaseUrl = sharedPrefs.getString(KEY_PREF_BASE_URL, "")

        CompanyApi.apiBaseUrl = apiBaseUrl!!
    }

    override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
       if (key == KEY_PREF_BASE_URL) {
            val newApiBaseUrl = sharedPreferences?.getString(key, "")
            CompanyApi.apiBaseUrl = newApiBaseUrl!!
       }
    }
2 Answers
object CompanyApi {
    val retrofitService: CompanyApiService by lazy {
    retrofit.create(CompanyApiService ::class.java)
}

This creates a singleton, you need to change that and re-create your Api when you changed your base_url however I wouldn't advise to do so. Creating a retrofit instance is consuming and you might get into errors later on.

Lucky for you Retrofit has a simple solution for that:

public interface UserManager {  
    @GET
    public Call<ResponseBody> userName(@Url String url);
}

The URL String should specify the full Url you wish to use.

also, check this out -> enter link description here

Related