Answer the question
In order to leave comments, you need to log in
How to make main thread wait for CallBack when using Retrofit?
I'm using Retrofit to parse complex Json. You have to use a lot of nested loops in the deserializer, so the response comes slower than the main thread returns the result from the function.
override fun getVideoInfo(id: String): Video? {
var video:Video? = Video(null)
retrofitClient.getVideoInfo(id).enqueue(object : Callback<VideoItemResponse> {
override fun onFailure(call: Call<VideoItemResponse>, t: Throwable) {
video = null
Log.e(VIDEO_ITEM_TAG, "Failure: $t.message" )
}
override fun onResponse(
call: Call<VideoItemResponse>,
response: Response<VideoItemResponse>
) {
video = response.body()?.item
Log.e(VIDEO_ITEM_TAG, "Response: ${video}")
}
})
Log.e(VIDEO_ITEM_TAG, "Before return: ${video}")
return video
}
2020-08-18 16:00:25.783 14824-14824/ru.app.yf E/Video item request: Before return: Video(videoId=null, title=null, duration=null, description=null, thumbnails={}, views=null)
2020-08-18 16:00:25.912 14824-14824/ru.app.yf E/Video item request: Response: Video(videoId=Chjs4xqYe0E, title=Влог из США. Я сделал ЭТО!, duration=PT15M37S, description=Регистрируйся в LetyShops и возвращай горящий кэшбэк
Thread.sleep(1000)
Log.e(VIDEO_ITEM_TAG, "Before return: ${video}")
return video
Answer the question
In order to leave comments, you need to log in
You call the request initially asynchronously with the enqueue() method. To run synchronously - use the execute() method. But as far as I know Android won't let you send a request on the UI thread.
PS
I would review the architecture of the application and instead of returning the received value in the method (via return), for example, directly in the callback, I would call another method, which would have received the answer.
You can also arrange all this more beautifully through RxJava + RxKotlin or coroutines.
You have to use a lot of nested loops in the deserializer
the response comes slower than the main thread, returns the result from the function.
video = response.body()?.item
Thread.sleep(1000)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question