Skip to content

Instantly share code, notes, and snippets.

@fvilarino
Last active April 19, 2021 23:05
Show Gist options
  • Save fvilarino/dc927c62fb04f700bd93227e872acbdb to your computer and use it in GitHub Desktop.
Save fvilarino/dc927c62fb04f700bd93227e872acbdb to your computer and use it in GitHub Desktop.
Base typed adapter
class TypedBaseAdapter<T : RecyclerViewBindingItem> :
RecyclerView.Adapter<RecyclerViewViewHolder<T>>() {
private val differ: AsyncListDiffer<T> by lazy(LazyThreadSafetyMode.NONE) {
AsyncListDiffer(this, Differ<T>())
}
private var items: List<T> by Delegates.observable(emptyList()) { _, _, new ->
differ.submitList(new)
}
override fun getItemCount(): Int = differ.currentList.size
override fun getItemViewType(position: Int): Int = items[position].type
@Suppress("UNCHECKED_CAST")
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerViewViewHolder<T> =
items.first { it.type == viewType }
.onCreateViewHolder(parent, viewType) as RecyclerViewViewHolder<T>
override fun onBindViewHolder(holder: RecyclerViewViewHolder<T>, position: Int) {
holder.bind(items[position])
}
fun update(items: List<T>) {
this.items = items
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment