在本教程的一部分中,我使用 LiveDataScope 从服务器获取列表的值并发出它,它工作正常。
现在我想用 SwipeRefreshLayout 再次刷新列表,但我不知道该怎么做。
其实我想重用liveDataScope代码来刷新列表。
我阅读了有关liveDataScope的android文档,如果我理解正确的话,如果liveData成功完成,它不会重新启动。
在这种情况下我不知道该怎么办。
视图模型:
val distanceLiveData: LiveData<List<Distance>>
= liveData(coroutineExceptionHandler) {
val distanceList = distanceRepository.getDistanceList()
emit(distanceList)
}
片段:
distanceViewModel.distanceLiveData.observe(viewLifecycleOwner) {
it?.let {
adapter.submitList(it as ArrayList<Distance>)
adapter.submitList(it)
binding.recyclerViewDistance.adapter = adapter
}
}
binding.swipeRefreshLayoutDistance.setOnRefreshListener {
//I need to refresh list here
}
在您的视图模型中,您应该公开一个方法来更新实时数据,例如:
private val _distanceLiveData = MutableLiveData<List<Distance>>()
val distanceLiveData: LiveData<List<Distance>> = _distanceLiveData
fun getDistanceList(){
val distanceList = distanceRepository.getDistanceList()
_distanceLiveData.value = distanceList
}
然后在你的片段调用方法来更新livedata
distanceViewModel.getDistanceList()
distanceViewModel.distanceLiveData.observe(viewLifecycleOwner) {
it?.let {
adapter.submitList(it as ArrayList<Distance>)
adapter.submitList(it)
binding.recyclerViewDistance.adapter = adapter
}
}
binding.swipeRefreshLayoutDistance.setOnRefreshListener {
distanceViewModel.getDistanceList()
}