如何在更新领域对象时收到通知

时间:2017-09-01 05:53:54

标签: android database realm

我有一张存储产品清单的表格。我希望只在任何行更新时才收到通知。我可以使用RealmChangeListener。下面是我的代码

 public void updateProducts(final List<Product> products) {
    Realm realmObj = Realm.getDefaultInstance();
    for (Product product : products) {
        if (product.shouldBeDeleted()) {
            delete(product.getBarcode());

        } else {
            realmObj.beginTransaction();
            realmObj.copyToRealmOrUpdate(product);
            realmObj.commitTransaction();
        }
    }
    realmObj.close();

}

3 个答案:

答案 0 :(得分:0)

是的,您可以使用领域更改侦听器... 我正在使用像我这样的项目

product.addChangeListener(new RealmChangeListener<RealmModel>() {
            @Override
            public void onChange(RealmModel realmModel) {
                //Your code when any row update or insert new record
            }
        });

有关详细信息,请参阅此链接

https://realm.io/docs/java/latest/api/io/realm/RealmChangeListener.html

答案 1 :(得分:0)

您可以使用我们的细粒度收集通知,该通知将报告已完成的修改类型:

RealmResults<Product> products = realm.where(Product.class).findAll();
products.addChangeListener(new OrderedRealmCollectionChangeListener<RealmResults<Product>>() {
  @Override
  public void onChange(RealmResults<Product> products, OrderedCollectionChangeSet changeSet) {
    for (int i : changeSet.getChanges()) {
      // Item at index i was updated
    }
  }
});

答案 2 :(得分:0)

 public void updateProducts(final List<Product> products) {
    try(Realm r = Realm.getDefaultInstance()) {
        r.executeTransaction((realm) -> {
            for (Product product : products) {
                if (product.shouldBeDeleted()) {
                    delete(product.getBarcode());
                } else {
                    realm.insertOrUpdate(product);
                }
            }
        });
    }    
}

UI线程上的其他地方:

private Realm realm;
private RealmResults<Product> results;
private RealmChangeListener<RealmResults<Product>> listener = (element) -> {
    if(element.isLoaded()) {
        // results are loaded, or a change occurred!
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.some_layout);
    realm = Realm.getDefaultInstance();
    results = realm.where(Product.class).findAllAsync();
    results.addChangeListener(listener);
}

@Override
public void onDestroy() {
    super.onDestroy(); 
    results.removeChangeListener(listener);
    results = null;
    realm.close();
}

P.S。您也希望在插入和删除时收到通知,否则您的UI将被取消同步。值得庆幸的是,这是默认行为。