Skip to content

Instantly share code, notes, and snippets.

@ElianFabian
Last active December 4, 2023 21:42
Show Gist options
  • Save ElianFabian/d3f138366669198ea187bcbabfaf1855 to your computer and use it in GitHub Desktop.
Save ElianFabian/d3f138366669198ea187bcbabfaf1855 to your computer and use it in GitHub Desktop.
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.AsyncListDiffer.ListListener
import androidx.recyclerview.widget.DiffUtil
import androidx.viewpager2.adapter.FragmentStateAdapter
abstract class FragmentStateListAdapter<T>(
fragmentManager: FragmentManager,
lifecycle: Lifecycle,
diffCallback: DiffUtil.ItemCallback<T>,
) : FragmentStateAdapter(fragmentManager, lifecycle) {
val currentList: List<T> get() = _differ.currentList
@Suppress("LeakingThis")
private val _differ = AsyncListDiffer(this, diffCallback)
init {
_differ.addListListener { previousList, currentList ->
onCurrentListChanged(previousList, currentList)
}
}
constructor(
fragment: Fragment,
diffCallback: DiffUtil.ItemCallback<T>,
) : this(
fragmentManager = fragment.childFragmentManager,
lifecycle = fragment.lifecycle,
diffCallback = diffCallback,
)
constructor(
fragmentActivity: FragmentActivity,
diffCallback: DiffUtil.ItemCallback<T>,
) : this(
fragmentManager = fragmentActivity.supportFragmentManager,
lifecycle = fragmentActivity.lifecycle,
diffCallback = diffCallback,
)
override fun getItemCount(): Int = _differ.currentList.size
protected fun getItem(position: Int): T = _differ.currentList[position]
protected fun getItemOrNull(position: Int): T? = _differ.currentList.getOrNull(position)
@JvmOverloads
fun submitList(items: List<T>, commitCallback: Runnable? = null) {
_differ.submitList(items, commitCallback)
}
fun addListListener(listener: ListListener<T>) {
_differ.addListListener(listener)
}
fun removeListListener(listener: ListListener<T>) {
_differ.removeListListener(listener)
}
protected open fun onCurrentListChanged(previousList: List<T>, currentList: List<T>) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment