kotlin - RecyclerView 未通过 Live Data Observer 更新
问题描述
我正在尝试在实时数据对象的观察响应中更新 recyclerView 适配器,但它不会更新 UI,如果我调试它,它会开始更新 UI。
看起来添加延迟使其工作或重新分配 recyclerView 项目适配器也可以工作,但我不明白为什么 notifyDataSetChanged 或 notifyItemRangeChanged 不起作用
以下是我正在使用的代码
adapter = MyAdapter(listOf())
binding.recyclerView.adapter = adapter
viewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
viewModel.data.observe(this, {
adapter.setData(it)
// This updates the UI, but this is not the right way to do so
//binding.recyclerViewData.adapter = adapter
})
我更新数据的适配器类
fun setData(data: MutableList<DataModelRoom>) {
this.data= data
notifyItemRangeChanged(0, data.size)
}
ViewModel 部分代码
var data: MutableLiveData<MutableList<DataModel>> = MutableLiveData()
/* This is part of init method */
viewModelScope.launch {
Amplify.Hub.subscribe(HubChannel.DATASTORE) { event ->
if (event.name == DataStoreChannelEventName.READY.toString()) {
isAmplifyDataReady.postValue(true)
data.postValue(repository.getDataFromAmplify())
}
Log.i(Logging.TAG_AMPLIFY, "event: $event")
}
/* Starting the DataStore Syncing */
Amplify.DataStore.start(
{ Log.i(Logging.TAG_AMPLIFY, "DataStore started") },
{ Log.e(Logging.TAG_AMPLIFY, "Error starting DataStore", it) }
)
}
recyclerView的布局部分
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="152dp"
android:orientation="horizontal"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewView" />
解决方案
我认为你把问题复杂化了。使用ListAdapter<T, K>
(包含在平台中并调用adapter.submitList(pass_the_new_list_here)
并让(必需的)DiffUtil.Callback
处理差异并更新所需内容。
推荐阅读
- c++ - regexec 和 pcre_exec 有什么区别?
- linux - 特定文件夹中的 Git 克隆存储库,但保留默认文件夹名称
- r - 使用 R 重新投影 MODIS 数据(结果为 NA 或没有空间范围)
- javascript - 为什么我在 webassembly 中导出的快速排序比纯 javascript 实现慢?
- java - Android - getter/setter 不传递一个特定的字符串
- jupyter-notebook - jupyter-notebook 是否可以安全地添加到公共存储库中
- python - 如何判断 VLC MediaListPlayer 的进度?
- java - 音频上下文中的两个增益以某种方式相互连接
- python - 如何映射多个数据框?
- java - Apache Ignite - 从缓存中获取所有内容