Hello, thank you for your comment.
The issue you describe (losing the RecyclerView position) is quite common but has nothing to do with the techniques described in this article.
I understand it is tempting to keep a reference to a RecyclerView adapter in the Fragment and reuse it from one RecyclerView to the next because it looks like it solves that issue, but this must be avoided because it creates memory leaks.
An adapter is part of the view layer and contains View references. When you set an adapter on a RecyclerView, the RecyclerView registers itself as a new listener on the adapter and unless you unregister it manually, the adapter will keep a reference to the RecyclerView forever, even after the Fragment View has been destroyed. The leak goes worse over time, as each new RecyclerView registers itself as an additional listener on the same adapter.
The scroll position is part of the saved instance state of the RecyclerView. Instance state is saved and restored automatically by the Fragment/Activity so you don't have to deal with it. This even works after the app process is killed and later restored.
By default, the RecyclerView will try to restore the scroll position as soon as an adapter is set on it. The problem is that this is often too early, as the adapter is usually initially empty and gets populated only after the View state has been restored (especially if the ViewModel does not properly cache the data). When the scroll position is restored and the adapter is empty, it will reset to 0 because that's the only position it can scroll to at that moment.
To solve this issue, you need the delay the scroll position restoration. There are 2 ways to do this:
- Old way (a bit hacky): set the adapter on the RecyclerView only after it has been populated with data. Make sure you don't reset the same adapter again the next times or the content animations will not play properly and views may not be recycled properly as the data gets updated.
- New way (recommended): when initializing the adapter, call setStateRestorationPolicy(PREVENT_WHEN_EMPTY). This will prevent the state, including the scroll position, from being restored until the adapter has at least one item to show. Note that PagingDataAdapter already does this automatically.
You can also use the PREVENT policy to delay the restoration, and set it back to the ALLOW policy after the adapter has been fully populated, in case you want to wait for more data to arrive before restoring the scroll position.
I hope this was helpful.