Last active
April 19, 2021 23:05
-
-
Save fvilarino/dc927c62fb04f700bd93227e872acbdb to your computer and use it in GitHub Desktop.
Base typed adapter
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
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