Room返回Flow列表结果时实现distinctUntilChanged等效去重的方法
针对Room返回Flow<List>场景的去重方案
distinctUntilChanged() 默认使用equals()方法比较前后发射值是否相等,在Flow<List<MyObject>>场景下失效的核心原因通常是实体类未正确重写equals()和hashCode(),或是你需要自定义更灵活的列表变更判断规则。以下是三种可直接落地的方案:
方案1:重写实体类equals与hashCode
如果你的实体类都用Kotlin data class 定义,编译器会自动生成包含所有字段比较逻辑的equals()、hashCode()方法,此时只要列表元素数量、顺序、每个元素的字段值完全一致,List.equals()就会返回true,默认的distinctUntilChanged()即可直接生效。
注意:如果通用基类
BaseEntity不是data class,需要手动在基类中重写equals()、hashCode(),覆盖所有通用基础字段的比较逻辑,子类有自定义字段也要同步重写。
代码示例:
// 基类示例,用data class自动生成equals逻辑 abstract data class BaseEntity( val id: Long, val createTime: Long, // 其他通用基础字段 ) // 子类继承基类,同样用data class定义 data class MyObject( val customField: String, // 其他自定义业务字段 ) : BaseEntity()
改造完成后直接调用默认方法即可:
roomDao.getMyObjectListFlow() .distinctUntilChanged() .collect { // 仅列表真实发生变更时触发回调 }
方案2:自定义比较规则
如果你不需要比较全部字段、或是不想修改原有实体类的equals()逻辑,可以给distinctUntilChanged()传入自定义比较器,自行定义"列表无变更"的判断规则。
比如仅比较列表元素的ID和数量,忽略其他字段变更:
roomDao.getMyObjectListFlow() .distinctUntilChanged { oldList, newList -> // 返回true代表两个列表无变更,不触发回调;返回false代表有变更 if (oldList.size != newList.size) return@distinctUntilChanged false oldList.zip(newList).all { (oldItem, newItem) -> oldItem.id == newItem.id } } .collect { // 符合自定义无变更规则时不会触发回调 }
该方案适配性更强,可以满足比如忽略元素顺序变更、忽略特定无关字段变更等特殊业务需求。
方案3:封装通用扩展方法
如果项目多处需要用到列表Flow的去重能力,可以封装成通用扩展方法提升复用性:
inline fun <T> Flow<List<T>>.distinctListUntilChanged( crossinline areItemsTheSame: (old: T, new: T) -> Boolean = { old, new -> old == new } ): Flow<List<T>> { return distinctUntilChanged { oldList, newList -> if (oldList.size != newList.size) false else oldList.zip(newList).all { (oldItem, newItem) -> areItemsTheSame(oldItem, newItem) } } }
使用示例:
// 默认使用equals比较所有字段 roomDao.getMyObjectListFlow().distinctListUntilChanged() // 传入自定义比较规则 roomDao.getMyObjectListFlow().distinctListUntilChanged { old, new -> old.id == new.id }
内容的提问来源于stack exchange,提问作者Shadow
相关产品推荐
相关产品推荐

