Tuesday 26 February 2019

Saving activity's state with onSaveInstanceState() and ViewModel

I was left with some questions regarding ViewModels after reading this:

https://developer.android.com/topic/libraries/architecture/saving-states

It says here that you should use a combination of both a ViewModel for configuration changes (like screen rotation), and using onSaveInstanceState() for all other cases where an activity is destroyed and then recreated in order to save the UI state.

My question is how do we know the way to restore the state when onCreate(Bundle) is called - should I use the ViewModel or should I use the bundle received as a parameter? When the configuration changes, onSaveInstanceState() is also called, and obviously onCreate() is always called.

If I only restore the state from a ViewModel, it won't always remain with the correct data (since the activity could have been destroyed due to other reasons than configuration changes). If I only use the bundle I save in onSaveInstanceState() then why would I use a ViewModel to begin with?



from Saving activity's state with onSaveInstanceState() and ViewModel

No comments:

Post a Comment