获取改造异步调用的结果 [英] Get the result of retrofit async call
本文介绍了获取改造异步调用的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用改造来获取Web api的响应数据,但是响应数据的结果似乎不同步.
I tried to use retrofit to get the response data of web api, but the result of response data seems not sync as the same.
fun fetchData(): LiveData<String> {
val auth = Credentials.basic(name, pass)
val request: Call<JsonElement> = webApi.fetchData()
val response: MutableLiveData<String> = MutableLiveData()
request.enqueue(object : Callback<JsonElement> {
override fun onFailure(call: Call<JsonElement>, t: Throwable) {
Log.e(TAG, "Failed to fetch token", t)
}
override fun onResponse(call: Call<JsonElement>, response: Response<JsonElement>) {
response.value = response.body()
Log.d(TAG, "response: ${response.value}") // I can get the result of response
}
})
return response // But the function return with the null
}
您可能需要处理程序.
You might need handler.
推荐答案
enqueue方法不等待响应,因此返回响应中的null结果是正常的.
The enqueue method doesn´t wait to the response so is normal the null result in your return response.
要解决此问题,您无需返回任何内容,只需将您的livedata放在作用域类中并更新值:
To solve this, you doesn´t need to return nothing, only put your livedata in the scope class and update the value:
class YourClass {
private var responseMutableLiveData: MutableLiveData<String> = MutableLiveData()
val responseLiveData: LiveData<String>
get() = responseMutableLiveData
fun fetchData() {
webApi.fetchData().enqueue(object : Callback<JsonElement> {
override fun onFailure(call: Call<JsonElement>, t: Throwable) {
Log.e(TAG, "Failed to fetch token", t)
}
override fun onResponse(call: Call<JsonElement>, response: Response<JsonElement>) {
responseMutableLiveData.postValue(response.body())
Log.d(TAG, "response: ${response.value}")
}
})
}
}
观察到实时数据,并且当值更改时,另一个类对其进行反应.
The livedata is observed and, when the value changes, then the other class reacts to it.
这篇关于获取改造异步调用的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文