How can I return a value after a callback in kotlin, I tried using Thread.sleep but it doesn't work
fun searchColorFromAPI(): Colors {
val service: RetrofitService = ServiceGenerator.createService(RetrofitService::class.java)
val result: MutableList<String> = arrayListOf()
val call: Call<Colors?>? = service.unityConverter(result)
call?.enqueue(object : Callback<Colors?> {
override fun onResponse(call: Call<Colors?>?, response: Response<Colors?>) {
//switchProgressVisibility()
if (response.isSuccessful) {
val serviceResponse: Colors? = response.body()
if (serviceResponse != null) {
mColors = serviceResponse
}
else {
//buildToast(getString(R.string.null_response))
}
}
else {
//buildToast(getString(R.string.response_unsuccessful))
val errorBody: ResponseBody = response.errorBody()
Log.e(TAG, errorBody.toString())
}
}
override fun onFailure(call: Call<Colors?>?, t: Throwable?) {
/* buildToast(getString(R.string.error_calling_service))
Log.e(TAG, t?.message)*/
}
})
return mColors
}
Always, the mColors is returned before the onFailure or onResponse because they're asynchronous. Before this code was in MainActivity but I was advised to take off, but now when I try get mColors I get the empty value before and after the onResponse is executed, please I'm still learning Kotlin and Android.
Your problem stems from the fact that
Retrofit
call
isasynchronous
, so as soon as you callsearchColorFromAPI
it returns youmColors
but theAPI
call may not have been made yet, so you get the mColors value before API call.To solve this issue, you can do
Use
callback
, this will require little modification in your current setup, but the 2nd option is preferable over this. Usingcallback
your function should look like this.And in your
activity
declare afunction
as follows.And now call to
searchColorFromApi
should look like thisUse Live Data, declare following
field
in yourviewmodel
, if you are not usingviewmodel
then declare it in theclass
which hassearchColorFromApi
function.and modify your
searchColorFromAPI
function as followsand in your
activity
do following