Search code examples
androidperformanceandroid-recyclerviewandroid-viewpager

What is the best way of notifying RecylerView about dataset changes when these changes happen in a ViewPager?


I've looked up the documentation of RecyclerView.Adapter to find out how different notify... methods work. It states

If you are writing an adapter it will always be more efficient to use the more specific change events if you can. Rely on notifyDataSetChanged() as a last resort.

Clicking an item of my RecyclerView starts an activity containing a ViewPager. The ViewPager uses FragmentStatePagerAdapter. As a result I am able to swipe views and make changes in them if I wish to do so. When my pager hosting activity is finished, I have to notify the adapter of the RecyclerView about the changes. I can only see 2 possible ways to proceed:

  1. I can set up a communication channel like this: fragments of the pager notify the hosting activity if they are edited -> the hosting activity sends a list of all the changes to the parent activity when it finishes -> the parent activity calls notifyItemChanged() on the RecylerView.Adapter for all the changes. I cannot think of a way of implementing this that is not ugly.
  2. I say that this is the last resort and bluntly call 'notifyDataSetChanged()` and the problem is gone but there is no proof that it won't slow down the app.

I'm quite new to this so maybe I'm missing an obvious solution.


Solution

  • I think both approaches can be applied depending on the situation. To make a correct decision you should consider potential amount of items which will be changed and a total amount of items in your list.

    Not so many total items or many changes - use notifyDataSetChanged.

    A lot of list items or single change - use 1st approach.

    Approach #1 can be easily implemented by calling startActivityForResult and expect back in onActivityResult a list of changed items' ids.

    Don't forget - you can always measure and compare performances for both approaches.