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!!
}
}