Skip to content

Instantly share code, notes, and snippets.

@oscarg798
Created April 24, 2020 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oscarg798/9d617fbaa9a591ac20a4bd0d37afd47b to your computer and use it in GitHub Desktop.
Save oscarg798/9d617fbaa9a591ac20a4bd0d37afd47b to your computer and use it in GitHub Desktop.
class ProductAdapter(
private val products: ArrayList<ViewProduct>
) : RecyclerView.Adapter<ProductViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
return ProductViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.product_item, parent, false)
)
}
override fun getItemCount(): Int = products.size
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
holder.bind(products[position])
}
override fun onBindViewHolder(
holder: ProductViewHolder,
position: Int,
payloads: MutableList<Any>
) {
if (payloads.isEmpty()) {
onBindViewHolder(holder, position)
} else {
for (data in payloads) {
when (data as Int) {
INVALID_PRODUCT_POSITION -> holder.updateProductQuantity(products[position].quantityInCart)
}
}
}
}
fun updateProducts(products: List<ViewProduct>) {
val result = DiffUtil.calculateDiff(ProductDiffUtilCallback(this.products, products))
result.dispatchUpdatesTo(this)
this.products.clear()
this.products.addAll(products)
}
fun removeProduct(product: ViewProduct) {
val index = products.indexOf(product)
if (index == INVALID_PRODUCT_POSITION) {
return
}
products.removeAt(index)
notifyItemRemoved(index)
}
companion object {
private const val INVALID_PRODUCT_POSITION = 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment