itarill
itarill

Reputation: 343

androidViewModel + recyclerview scroll jump on model update (MVVM)

I have a very specific issue with a recyclerview + mvvm implementation.

When I select a ListItem in the recyclerview, the click is given to my viewmodel class, which applies the "isselected" flag on the ListItem plus the MutableLiveData class that is observed (indirectly) by the recyclerview. This causes the observer in the mainactivity to update the whole List<ListItem> which is displayed by the recyclerview.

The result is that whenever I select an item in the recyclerview, the recyclerview will scroll up, (presumably) because the whole list is updated, and it treats the updated list as a whole new list.

How can this behavior be adjusted in a clean code, preferably mvvm pattern.

(Maybe a solution in which the position of the click was recorded, and the new list is "scrolled" to this position immediately, if the position exists. But I don't know how to implement this, if possible.)

Upvotes: 0

Views: 1605

Answers (1)

itarill
itarill

Reputation: 343

Turns out this is a pretty common problem, but my search wording with google was misleading me.

This stackoverflow answer solved my problem:

Refreshing data in RecyclerView and keeping its scroll position

//add a Parcelable field to save the state
private Parcelable recyclerViewState;

//before updating the adapter with live data
recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();

//after updating the adapter with live data
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);

Upvotes: 2

Related Questions