Skip to content

Instantly share code, notes, and snippets.

@yongjhih
Created May 28, 2020 18:59
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 yongjhih/391eb21eac8017178e2edac735e5034e to your computer and use it in GitHub Desktop.
Save yongjhih/391eb21eac8017178e2edac735e5034e to your computer and use it in GitHub Desktop.
open class LoadingPagedListAdapter<T, VH : RecyclerView.ViewHolder>(
private val onOnCreateViewHolder: LoadingPagedListAdapter<T, VH>.(parent: ViewGroup, viewType: Int) -> VH,
private val onOnBindViewHolder: LoadingPagedListAdapter<T, VH>.(holder: VH, position: Int) -> Unit,
private val onGetItemViewType: LoadingPagedListAdapter<T, VH>.(Int) -> Int = { 0 },
private val lifecycle: LiveData<DataSourceLifecycle>,
differ: DiffUtil.ItemCallback<T>,
private val onCreateLoadingViewHolder: (LoadingPagedListAdapter<T, VH>.(parent: ViewGroup, viewType: Int) -> RecyclerView.ViewHolder)? = null
) : PagedListAdapter<T, RecyclerView.ViewHolder>(differ) {
companion object {
const val LOADING_TYPE = 19841119
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
lifecycle.observeForever {
if (it == Loading) {
notifyItemInserted(itemCount)
} else {
notifyItemRemoved(itemCount)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == LOADING_TYPE) {
onCreateLoadingViewHolder?.invoke(parent, viewType) ?:
object : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context)
.inflate( R.layout.loading_indicator, parent, false)
) {}
} else {
onOnCreateViewHolder(parent, viewType)
}
}
override fun getItemViewType(position: Int): Int {
return if (isLoading() && position == itemCount - 1) {
LOADING_TYPE
} else {
onGetItemViewType(position)
}
}
@Suppress("UNCHECKED_CAST")
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder as? VH)?.let { onOnBindViewHolder(it, position) }
}
private fun isLoading(): Boolean {
return lifecycle.value == Loading
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment