tqn
tqn

Reputation: 125

Stop Realm listener is called when a attribute is changed

I am using Realm with RxJava Observable callback. My problem is when user interact and change a attribute in realm, the callback is call continuous and crash the UI.
I only want the realm listener when any data is inserted, or deleted to keep data synching. Is it possible in Realm?

Edit:
When my recyclerView is shown, it will set every item to seen state, it mean that all item will be saved to realm with seen value. So it's reason that I don't want realm Observable is called too many times. I'm looking for some way that make realm stop listener when I set data to seen state, but it's also difficult to handle in RecyclerView adapter. Fortunately, my data could be edited this attribute only, so I just want to keep it synchronize when item is inserted or deleted, this way could be acceptable. Seem like realm is really fast, but it's really hard to control in some situation.

Upvotes: 1

Views: 348

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81539

I just want to keep it synchronize when item is inserted or deleted,

That's really easy, just use RealmRecyclerViewAdapter like this:

public class MyAdapter extends RealmRecyclerViewAdapter<MyRealmObject, ViewHolder> {
    public MyAdapter(OrderedRealmCollection<T> results) {
        super(results, 
              true /* add a RealmChangeListener to keep adapter in sync */, 
              false /* ignore "changes" and only care about insert/delete */);
    }

    /* onCreateViewHolder, onBindViewHolder, ViewHolder */    
}

And you can use RealmObjectChangeListener if you want to still listen for changes and update the items when this is required.

MyObject myObject;

if(myObject != null && myObject.isValid()) {
    myObject.removeAllChangeListeners();
}
myObject = ..
myObject.addChangeListener(new RealmObjectChangeListener<MyObject>() {
    ... // receive "field set" and whether it is changed
    // make sure you return out if `changeSet.isDeleted() == true`
}

Upvotes: 0

Related Questions