我发现只要数据库中的行被更新,Dao 返回的 LiveData 就会调用它的观察者,即使 LiveData 值显然没有改变。
考虑如下例所示的情况:
示例实体
@Entity
public class User {
public long id;
public String name;
// example for other variables
public Date lastActiveDateTime;
}
示例道
@Dao
public interface UserDao {
// I am only interested in the user name
@Query("SELECT name From User")
LiveData<List<String>> getAllNamesOfUser();
@Update(onConflict = OnConflictStrategy.REPLACE)
void updateUser(User user);
}
后台线程中的某处
UserDao userDao = //.... getting the dao
User user = // obtain from dao....
user.lastActiveDateTime = new Date(); // no change to user.name
userDao.updateUser(user);
用户界面中的某处
// omitted ViewModel for simplicity
userDao.getAllNamesOfUser().observe(this, new Observer<List<String>> {
@Override
public void onChanged(@Nullable List<String> userNames) {
// this will be called whenever the background thread called updateUser.
// If user.name is not changed, it will be called with userNames
// with the same value again and again when lastActiveDateTime changed.
}
});
在此示例中,ui 仅对用户名感兴趣,因此对 LiveData 的查询仅包含名称字段。然而,即使只有其他字段被更新,observer.onChanged 仍然会在 Dao Update 上被调用。
(事实上,如果我不对 User 实体进行任何更改并调用 UserDao.updateUser,observer.onChanged 仍然会被调用)
这是Dao LiveData在Room中的设计行为吗?我是否有机会解决这个问题,以便仅在更新所选字段时才会调用观察者?
编辑:我更改为使用以下查询将 lastActiveDateTime 值更新为评论建议中的 KuLdip PaTel。仍然调用用户名的LiveData的观察者。
@Query("UPDATE User set lastActiveDateTime = :lastActiveDateTime where id = :id")
void updateLastActiveDateTime(Date lastActiveDateTime, int id);