【问题标题】:Get the result of retrofit async call获取改造异步调用的结果
【发布时间】:2020-02-28 07:21:08
【问题描述】:

我尝试使用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
}

你可能需要处理程序。

【问题讨论】:

标签: android retrofit android-livedata


【解决方案1】:

enqueue 方法不会等待响应,因此返回响应中的 null 结果是正常的。

要解决这个问题,您不需要返回任何内容,只需将您的 livedata 放入范围类并更新值:

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

观察实时数据,当值发生变化时,其他类会对其做出反应。

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2016-03-05
    • 2014-01-19
    • 1970-01-01
    相关资源
    最近更新 更多