Skip to content

Recommendations for the DiffUtil Support

Vitaly Vivchar edited this page Feb 22, 2018 · 8 revisions

Step 1: Create the BaseViewModel interface

public interface BaseViewModel extends ViewModel {

	int getID();
}

Step 2: Replace the interface for all your models

public class YourViewModel implements BaseViewModel {

        /* your code */

        @Override
        public int getID() { /* your code */ }
}

Step 3: Override equals and hashCode methods

public class YourViewModel implements BaseViewModel {

        /* your code */

        @Override
        public int getID() { /* your code */ }

        @Override
        public boolean equals(Object object) { /* your implementation */ }

        @Override
        public int hashCode() { /* your implementation */ }
}

Step 4: Implement your DiffCallback class and override the areItemsTheSame method

public class YourDiffCallback extends DefaultDiffCallback<BaseItemModel>() {
        
        @Override
        public boolean areItemsTheSame(BaseItemModel oldItem, BaseItemModel newItem) {
                return oldItem.getID() == newItem.getID();
        }
}

Step 4: Set your DiffCallback to adapter

adapter.setDiffCallback(new YourDiffCallback());