检查领域对象是否有任何更改

时间:2016-07-20 03:16:42

标签: java android realm

如果结果中的realmObject的值发生了变化,有没有办法检测它?

Account account = mRealmInstance.where(Account.class).equalTo("isLoggedIn", true).findFirst();

account.setName("New Name");

if(account.hasChanged()){ //Is there a realmMethod for this?

}

1 个答案:

答案 0 :(得分:3)

我认为这就是你要找的东西?

RealmChangeListener<Account> listener = new RealmChangeListener() {
    @Override
    public void onChange(Account account) {
        // changes have been made to Account table
    }
}

Account mAccount;

mAccount = mRealmInstance.where(Account.class).equalTo("isLoggedIn", true).findFirst();
if(mAccount != null) {
    mAccount.addChangeListener(listener);
    //assuming I'm in a transaction here
    mAccount.setName("New Name");
}

...

if(mAccount.isValid()) {
    mAccount.removeAllChangeListeners();
}

虽然我认为只要RealmChangeListener表发生更改,Account就会被激活,而不仅仅是在修改此特定对象时。

(编辑:因为Realm 3.1+领域对象监听器也是细粒度的,因此只有在修改所选帐户时才会对其进行修改)