【发布时间】:2021-05-27 01:37:37
【问题描述】:
我的viewmodel 中有此功能,我想通过获取请求检索位置列表。
但是当我从片段中调用函数fetchAllLocations 时,该函数返回null。但在onResponse 方法中,列表位置不为空。我不知道为什么位置在onResponse 方法之外为空。
fun fetchAllLocations(): List<Location>?
{
val call = apiInterface?.fetchAllLocation()
var locations: List<Location>? = null
call?.enqueue(object : Callback<List<Location>> {
override fun onResponse(call: Call<List<Location>>, response: Response<List<Location>>) {
locations = response.body()
}
override fun onFailure(call: Call<List<Location>>, t: Throwable) {
}
})
return locations
}
}
【问题讨论】:
-
因为是异步进程
-
这是由于异步行为。 call?.enqueue 是一个异步操作。因此,当此 API 调用时,它会返回响应回调下的位置列表。由于您要返回位置,因此 fetchAllLocations 将始终返回空位置。
-
那我应该如何检索数据?
-
您可以在 ViewModel 中使用实时数据并从片段中观察此实时数据,而不是返回。在 onResponse 回调中,在 livedata 中发布值
-
你有一个例子我怎么能做到这一点?
标签: android kotlin retrofit get-request