Created
May 28, 2020 18:59
-
-
Save yongjhih/391eb21eac8017178e2edac735e5034e to your computer and use it in GitHub Desktop.
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
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