首页 > 解决方案 > 改造入队请求在 onResponse 方法中不返回 liveData

问题描述

当我使用改造请求从 web api 获取值时,然后将其分配给 liveData。但它总是在将值设置为 onResponse 中的 responseLiveData 之前返回 null。

fun fetchContents(): LiveData<String> {
    val responseLiveData: MutableLiveData<String> = MutableLiveData()
    val flickrRequest: Call<String> = flickrApi.fetchContents()

    flickrRequest.enqueue(object : Callback<String> {

        override fun onFailure(call: Call<String>, t: Throwable) {
            Log.e(TAG, "Failed to fetch photos", t)
        }

        override fun onResponse(
            call: Call<String>,
            response: Response<String>
        ) {
            Log.d(TAG, "Response received")
            responseLiveData.value = response.body()
        }
    })

    return responseLiveData
}

// then assign to the liveData in viewModel
val flickrLiveData: LiveData<String> = FlickrFetchr().fetchContents()

来自大书呆子牧场指南的这段代码,我发现它无法正常工作,所以我发出了这个错误。

标签: androidretrofitandroid-livedata

解决方案


推荐阅读