基于 table 修改的房间检查失效

Room checks invalidations based on table modifications

Note: Room checks invalidations based on table modifications, which means it may dispatch false positive notifications. Guide to app architecture

什么是 Room 的失效?它如何导致误报通知?

也就是说,

假设您有以下查询

@Query(“SELECT * FROM Users WHERE userId = :id)
fun getUser(id: String): LiveData<User>

而你正在观察它

getUser("id_1").observe(this, Observer{
    // do something 
})

上面的方法没有问题,但是有误报的情况。

现在假设您从其他地方删除了 userId = "id_2" 的用户。此时,您知道您不需要收到之前的 getUser("id_1") 调用的通知,因为它与您在 id_2 上的操作无关。但您仍然会收到通知,并且您的 // do something 会再次 运行。那是因为,Room 会知道有什么东西被改变了,但不知道改变了什么,因此它只会重新查询并再次发送结果。

为了绕过这个误报通知,当你有 LiveData 作为 return 类型时,你可以使用 MediatorLiveData 或者 distinctUntilChanged 如果你有 RxJava 作为 return 输入您的 Daos。

参考:7 Pro-tips for Room