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
Retrofitcallisasynchronous, so as soon as you callsearchColorFromAPIit returns youmColorsbut theAPIcall 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. Usingcallbackyour function should look like this.And in your
activitydeclare afunctionas follows.And now call to
searchColorFromApishould look like thisUse Live Data, declare following
fieldin yourviewmodel, if you are not usingviewmodelthen declare it in theclasswhich hassearchColorFromApifunction.and modify your
searchColorFromAPIfunction as followsand in your
activitydo following