Android 获取改装异步调用的结果

Android 获取改装异步调用的结果,android,retrofit,android-livedata,Android,Retrofit,Android Livedata,我尝试使用改造来获取web api的响应数据,但响应数据的结果似乎不同步 fun fetchData(): LiveData<String> { val auth = Credentials.basic(name, pass) val request: Call<JsonElement> = webApi.fetchData() val response: MutableLiveData<String> = MutableLiveDa

我尝试使用改造来获取web api的响应数据,但响应数据的结果似乎不同步

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
}
fun fetchData():LiveData{
val auth=Credentials.basic(名称、过程)
val请求:Call=webApi.fetchData()
val响应:MutableLiveData=MutableLiveData()
排队(对象:回调{
覆盖失效时的乐趣(调用:调用,t:可丢弃){
Log.e(标记“无法获取令牌”,t)
}
覆盖fun onResponse(调用:调用,响应:响应){
response.value=response.body()
Log.d(标记,“response:${response.value}”)//我可以得到response的结果
}
})
return response//但函数返回null
}


您可能需要处理程序。

排队方法不会等待响应,因此返回响应中的空结果是正常的

要解决这个问题,您不需要什么都不返回,只需将livedata放入scope类并更新值:

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}")  
        }
    })
   }
}
classyourclass{
私有变量responseUMatableLiveData:MutableLiveData=MutableLiveData()
val responseLiveData:LiveData
get()=responseUMTableLiveData
fun fetchData(){
webApi.fetchData().enqueue(对象:回调{
覆盖失效时的乐趣(调用:调用,t:可丢弃){
Log.e(标记“无法获取令牌”,t)
}
覆盖fun onResponse(调用:调用,响应:响应){
responseUMTableLiveData.postValue(response.body())
Log.d(标记“response:${response.value}”)
}
})
}
}
观察livedata,当值发生变化时,另一个类会对此作出反应。

看一看