获取改装异步调用的结果

Get the result of retrofit async call

我试过用retrofit获取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
}

您可能需要处理程序。

入队方法不等待响应,因此 return 响应中的空结果是正常的。

要解决这个问题,您不需要 return 什么,只需将您的实时数据放在范围 class 中并更新值:

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}")  
        }
    })
   }
}

观察实时数据,当值发生变化时,另一个 class 会对其做出反应。