Forked from NikolaDespotoski/ProductListDiffCallback.java
Last active
July 6, 2017 14:31
-
-
Save JonathanPrecise/98157e28b9d839e0ff21ee8d4cd5d07c to your computer and use it in GitHub Desktop.
Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.despotoski.nikola.diffutilexample; | |
import android.os.Bundle; | |
import android.support.annotation.Nullable; | |
import android.support.v7.util.DiffUtil; | |
import java.util.List; | |
/** | |
* 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(Product.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.isEmpty()) return null; | |
return diffBundle; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment