Trying to refactor GeoQuiz to follow MVVM, but running into trouble when configuration changes


#1

I got everything working, except retaining state when the user rotates the screen (or any configuration change for that matter).

While doing research I’ve come across several options, but I can’t figure out which one is right (if there even is only one “right” way).

1.(onSaveInstanceState: can’t be used in the ViewModel, this only works in activities/fragments)
2. Extending the ViewModel class. This is apparently made to make it easier to store UI-related data across the lifecycle. I find it quite confusing, and it seems overkill for what my app does. There are no async requests to online databases, feeds, or whatsoever. More than that: I can’t use @Bindable anymore, so I don’t know how to make the binding with my View.
3. Using fragments to persist state. This is used in Google’s own todo-mvvm-databinding sample. I find it strange to use Fragments for this. They don’t seem to be made for the purpose of just storing data.

Which one is the “best”? And why?

Code can be found here: https://github.com/hdeweirdt/GeoQuiz/tree/refactor_to_mvvm


#2

Going with the first option, I would probably advise using activity/fragment as a helper controller component.
You can go about doing that by saving the index position of the currently viewed item in the onSaveInstance() in the onPause() lifecycle callback. Upon completion of the screen rotation when the activity is re-instantiated, check for savedInstanceState != null and get the index position from the bundle and pass it to the viewmodel (probably a new setter method) and also have the RecyclerView smooth scroll to this position and proceed as usual. Theoretically, this should work. :slightly_smiling_face: