Use setRecycledViewPool for Optimizing Nested RecyclerView

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
Use setRecycledViewPool for Optimizing Nested RecyclerView

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we will learn about how can we optimize the scrolling performance of the Nested RecyclerView using the setRecycledViewPool.

When we use RecyclerView, it reuses the items from the recycled view pool wherever possible for performance optimization.

But suppose we have a Nested RecyclerView as below:

- OuterRecyclerView
    - InnerRecyclerViewOne
    - InnerRecyclerViewTwo

And we have similar view types in both the InnerRecyclerViewOne and InnerRecyclerViewTwo.

The optimization works for that particular RecyclerView because that particular RecyclerView has its own View Pool. Here InnerRecyclerViewOne and InnerRecyclerViewTwo are independent of each other in terms of the recycled view pool.

It means that the InnerRecyclerViewOne will not share anything with the InnerRecyclerViewTwo although they have similar view types. The pool does not get shared between the two RecyclerViews even though they are having similar types of views.

If they can share the recycled view pool, it will lead to better performance.

For that, we use the setRecycledViewPool.

So, we create a single view pool and pass it to the both RecyclerViews using the setRecycledViewPool so that it gets shared as below:

class OuterRecyclerViewAdapter() : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    // code removed for brevity

    private val viewPool = RecyclerView.RecycledViewPool()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        // code removed for brevity

        viewHolderOne.innerRecyclerViewOne.setRecycledViewPool(viewPool)

        // code removed for brevity

        viewHolderTwo.innerRecyclerViewTwo.setRecycledViewPool(viewPool)

    }

    // code removed for brevity

}

This will improve the scrolling performance as it will start reusing the view from the shared view pool.

This is how we can use the setRecycledViewPool to improve the scrolling performance while having the Nested RecyclerView.

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.