Junior — Middle
What is the difference between storing data in ViewModel and using the onSaveInstanceState method to save the application's state?
sobes.tech AI
Answer from AI
ViewModel and onSaveInstanceState are used to preserve state, but they work differently and are intended for different purposes.
-
ViewModel stores data in memory tied to the lifecycle of an Activity or Fragment. It survives configuration changes like screen rotations, preserving data without needing to reload it. However, when the app process is completely destroyed (e.g., due to low memory), data in ViewModel is lost.
-
onSaveInstanceState saves small amounts of data in a Bundle object, which is serialized and restored by the system when the Activity is recreated after process termination. This method is suitable for saving simple and small data (e.g., UI state), but not for large or complex objects.
Example:
class MyViewModel : ViewModel() {
var userData: String? = null
}
// In Activity
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
// onSaveInstanceState
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("key", "value")
}
// Restoring in onCreate
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val value = savedInstanceState?.getString("key")
}
Summary:
- Use ViewModel to store data that should survive screen rotations.
- Use onSaveInstanceState to save state that needs to be restored after complete Activity or process destruction.