Search code examples
androidkotlinrealmrealm-mobile-platformrealm-list

Determine realm changeSet fields


How to determine what fields changed at RealmObject update with the basic realm adapter listener approach?

Need do have both ranges info and changed entity fields info.

fun notifyRecyclerViewOfChanges(changeSet: ChangeSet?) { 
   // ?
}

Solution

  • You can refer to the official realm-android-adapters to know how to put it together:

    private OrderedRealmCollectionChangeListener createListener() {
        return new OrderedRealmCollectionChangeListener() {
            @Override
            public void onChange(Object collection, OrderedCollectionChangeSet changeSet) {
                if (changeSet.getState() == OrderedCollectionChangeSet.State.INITIAL) { // before Realm 5.0, this is `changeSet == null`
                    notifyDataSetChanged();
                    return;
                }
                // For deletions, the adapter has to be notified in reverse order.
                OrderedCollectionChangeSet.Range[] deletions = changeSet.getDeletionRanges();
                for (int i = deletions.length - 1; i >= 0; i--) {
                    OrderedCollectionChangeSet.Range range = deletions[i];
                    notifyItemRangeRemoved(range.startIndex, range.length);
                }
    
                OrderedCollectionChangeSet.Range[] insertions = changeSet.getInsertionRanges();
                for (OrderedCollectionChangeSet.Range range : insertions) {
                    notifyItemRangeInserted(range.startIndex, range.length);
                }
    
                if (!updateOnModification) {
                    return;
                }
    
                OrderedCollectionChangeSet.Range[] modifications = changeSet.getChangeRanges();
                for (OrderedCollectionChangeSet.Range range : modifications) {
                    notifyItemRangeChanged(range.startIndex, range.length);
                }
            }
        };
    }
    

    If you need Field-level changes, then the RealmObject needs to have its own change listener using RealmObjectChangeListener, and updateOnModification should be false (as you want to handle it in the view holder itself).