https://kotlinlang.org logo
#codereview
Title
# codereview
e

edwardwongtl

01/16/2019, 6:04 AM
I got a simpler version but only support one viewType at a time
Copy code
class SimpleViewHolder<T>(view: View) : RecyclerView.ViewHolder(view)

class RxAdapter<T>(
    @LayoutRes private val layoutId: Int,
    private val binding: (View, T) -> Unit
) : ListAdapter<T, SimpleViewHolder<T>>(DiffCallback<T>()) {
    private val signal by lazy { PublishSubject.create<Pair<Int, T>>() }
    val itemClicks by lazy { signal as Observable<Pair<Int, T>> }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleViewHolder<T> =
        SimpleViewHolder(parent.inflate(layoutId, false))

    override fun onBindViewHolder(holder: SimpleViewHolder<T>, position: Int) {
        binding(holder.itemView, getItem(position))
        holder.itemView.setOnClickListener { signal.onNext(holder.adapterPosition to getItem(holder.adapterPosition)) }
    }

    private class DiffCallback<T> : DiffUtil.ItemCallback<T>() {
        override fun areItemsTheSame(oldItem: T, newItem: T): Boolean = oldItem == newItem

        override fun areContentsTheSame(oldItem: T, newItem: T): Boolean = oldItem == newItem
    }
}
Forgive me for combining Rx into it, as it suits my need.
a

arekolek

01/16/2019, 8:46 AM
that
DiffCallback
doesn’t handle modifying an item
e

edwardwongtl

01/16/2019, 8:47 AM
When using data class, it actually can handle modified items, as the equals in data class is deep equal.
a

arekolek

01/16/2019, 8:48 AM
I’m saying your implementation of
DiffCallback
doesn’t handle it, think of what happens if an item changes one field
(it’s going to be treated as a removal + addition)
4 Views