Skip to content

Instantly share code, notes, and snippets.

@sergei-lapin
Created August 5, 2021 06:55
Show Gist options
  • Save sergei-lapin/5a23d060d648e00b083d207697693e99 to your computer and use it in GitHub Desktop.
Save sergei-lapin/5a23d060d648e00b083d207697693e99 to your computer and use it in GitHub Desktop.
Full Consumer code
class PrefetchViewPool(
private val defaultMaxRecycledViews: Int,
private val viewHolderSupplier: ViewHolderSupplier
) : RecyclerView.RecycledViewPool() {
private val recycledViewsBounds = mutableMapOf<Int, Int>()
init {
attachToPreventFromClearing()
viewHolderSupplier.viewHolderConsumer = ::putViewFromSupplier
viewHolderSupplier.start()
}
fun setPrefetchBound(viewType: Int, count: Int) {
recycledViewsBounds[viewType] = max(defaultMaxRecycledViews, count)
viewHolderSupplier.setPrefetchBound(viewType, count)
}
override fun putRecycledView(scrap: RecyclerView.ViewHolder) {
val viewType = scrap.itemViewType
val maxRecycledViews = recycledViewsBounds.getOrPut(viewType) { defaultMaxRecycledViews }
setMaxRecycledViews(viewType, maxRecycledViews)
super.putRecycledView(scrap)
}
override fun getRecycledView(viewType: Int): RecyclerView.ViewHolder? {
val holder = super.getRecycledView(viewType)
if (holder == null) viewHolderSupplier.onItemCreatedOutside(viewType)
return holder
}
override fun clear() {
super.clear()
viewHolderSupplier.stop()
}
private fun putViewFromSupplier(scrap: RecyclerView.ViewHolder, creationTimeNanos: Long) {
factorInCreateTime(scrap.itemViewType, creationTimeNanos)
putRecycledView(scrap)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment