Skip to content

Instantly share code, notes, and snippets.

@NikolaDespotoski
Created August 17, 2016 22:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save NikolaDespotoski/30822a7eeb01969b1b49f1cc36b0316a to your computer and use it in GitHub Desktop.
Save NikolaDespotoski/30822a7eeb01969b1b49f1cc36b0316a to your computer and use it in GitHub Desktop.
Sample
package com.despotoski.nikola.diffutilexample;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.util.DiffUtil;
import java.util.List;
import static com.despotoski.nikola.diffutilexample.Product.KEY_DISCOUNT;
/**
* Created by Nikola on 8/17/2016.
*/
public class ProductListDiffCallback extends DiffUtil.Callback {
private List<Product> mOldList;
private List<Product> mNewList;
public ProductListDiffCallback(List<Product> oldList, List<Product> newList) {
this.mOldList = oldList;
this.mNewList = newList;
}
@Override
public int getOldListSize() {
return mOldList != null ? mOldList.size() : 0;
}
@Override
public int getNewListSize() {
return mNewList != null ? mNewList.size() : 0;
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return mNewList.get(newItemPosition).getProductId() == mOldList.get(oldItemPosition).getProductId();
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return mNewList.get(newItemPosition).equals(mOldList.get(oldItemPosition));
}
@Nullable
@Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
Product newProduct = mNewList.get(newItemPosition);
Product oldProduct = mOldList.get(oldItemPosition);
Bundle diffBundle = new Bundle();
if (newProduct.hasDiscount() != oldProduct.hasDiscount()) {
diffBundle.putBoolean(KEY_DISCOUNT, newProduct.hasDiscount());
}
if (newProduct.getReviews().size() != oldProduct.getReviews().size()) {
diffBundle.putInt(Product.KEY_REVIEWS_COUNT, newProduct.getReviews().size());
}
if (newProduct.getPrice() != oldProduct.getPrice()) {
diffBundle.putFloat(Product.KEY_PRICE, newProduct.getPrice());
}
if (diffBundle.size() == 0) return null;
return diffBundle;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment