【发布时间】:2021-10-24 18:09:26
【问题描述】:
我需要从 MVVM 多次调用一种方法以进行 API 调用并将结果发送到回收器视图。我不知道用户需要这样做多少次,因为它取决于列表大小。例如:
list: ["FirstElement", "SecondElement", "..", "..."]
在代码中,我尝试了循环中的调用方法:
for (city in list) {
viewModel.getCurrentWeatherByCity(city, appID, unit).observe(viewLifecycleOwner, {
result.add(it) // here is arraylist for recyclerview
})
}
val adapterRecycler = LocationListWeatherRecyclerAdapter(result) // init adapter for recycler
setUpRecyclerData(adapterRecycler) // method for setup recyclerview
查看模型方法:
fun getCurrentWeatherByCity(city: String, appID: String, units: String): LiveData<WeatherModel> {
return repository.getCurrentWeatherByCity(city, appID, units)
}
和存储库方法:
fun getCurrentWeatherByCity(city: String, appID: String, units: String ) : LiveData<WeatherModel> {
apiService.getCurrentWeatherByCity(city, appID, units).enqueue(object : Callback<WeatherModel>{
override fun onResponse(call: Call<WeatherModel>, response: Response<WeatherModel>) {
if (response.isSuccessful) {
weatherData.postValue(response.body())
} else {
}
}
override fun onFailure(call: Call<WeatherModel>, t: Throwable) {
}
})
return weatherData
}
但我知道这是错误的解决方案,因为结果是在后台执行的并且是错误的。这个 for 可以从循环中的 4 次迭代中返回数组中的 80 项。
你知道我能做些什么吗? 感谢帮助
【问题讨论】:
-
你能展示你的
getCurrentWeatherByCity函数吗? -
@Tenfour04 更新了问题。你可以在那里看到:)