首页 > 解决方案 > 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" />

标签: kotlinandroid-recyclerviewaws-amplifyandroid-livedata

解决方案


我认为你把问题复杂化了。使用ListAdapter<T, K>(包含在平台中并调用adapter.submitList(pass_the_new_list_here)并让(必需的)DiffUtil.Callback处理差异并更新所需内容。


推荐阅读