具有相同内存引用 LiveData 与 Room DB 和 DiffUtil 的对象

Object with same memory reference LiveData with Room DB and DiffUtil

我正在尝试将列表与 Room DB 和 Diff Utils 集成,

面临的问题:

代码:

房间 - 听力变化:

@Query("SELECT * FROM tbl_topic_list ORDER BY created_at DESC")
abstract fun getTopicListLiveData():LiveData<List<FilteringTopicEntity>>

LiveData - 听力变化:

viewModel.getTopicListLiveData().observe(this, { list: List<FilteringTopicEntity> ->
            itemAdapter?.let {
                it.setData(list.toMutableList())
            }.orElse {
                itemAdapter = TopicListingAdapter(list
                    .toMutableList(), itemListener)
                itemTopicRecyclerView.adapter = itemAdapter
            }
            Log.e(TAG, "Item Received ${list.size}")
        })

正在插入数据库

@Update(onConflict = OnConflictStrategy.REPLACE)
abstract fun updateFilterTopic(copyDataEntity: FilteringTopicEntity)

正在更新数据库行值

    override fun updateTopic(topicEntity: FilteringTopicEntity) {
        topicEntity.updatedAt = DateTime()
        topicListDao.updateFilterTopic(topicEntity)
    }
class MediaDiffCallback(
        private val oldList: MutableList<FilteringTopicEntity>,
        private val newList: MutableList<FilteringTopicEntity>
    ) : DiffUtil.Callback() {

        override fun getOldListSize(): Int = oldList.size

        override fun getNewListSize(): Int = newList.size

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldList[oldItemPosition].id == newList[newItemPosition].id
        }

        override fun areContentsTheSame(oldPosition: Int, newPosition: Int): Boolean {
            return oldList[oldPosition].updatedAt ==  newList[newPosition].updatedAt
        }

        @Nullable
        override fun getChangePayload(oldPosition: Int, newPosition: Int): Any? {
            return super.getChangePayload(oldPosition, newPosition)
        }
    }

适配器完整代码:link

我尝试了几种解决方案那个问题没有任何效果

LiveData received items present already in the adapter without set

请帮助找出没有 notifyDataSetChanged() 方法的通知列表项更改,以便与 DiffUtils.

正确集成

问题已解决

最初,适配器中加载的列表项目和选定项目已更改并替换为数据库。

    @Update(onConflict = OnConflictStrategy.REPLACE)
    abstract fun updateFilterTopic(copyDataEntity: FilteringTopicEntity)

在这里,问题是我使用了房间数据库之前返回的相同项目实例。

So. I reassigned values to the new instance and updated it to DB, now updates receiving as expected.

open class FilteringTopicEntity() : com.support.room.BaseEntity(), Parcelable {
    fun copy(filteringTopicEntity: FilteringTopicEntity): FilteringTopicEntity {
        filteringTopicEntity.id = id
        filteringTopicEntity.updatedAt = updatedAt
        filteringTopicEntity.createdAt = createdAt
        return filteringTopicEntity
    }
}

这里我展示了我是如何复制一个值的

    filteringTopicEntity.copy(FilteringTopicEntity()