Middle
What is the difference between ViewModel and OnSavedInstanceState in Android?
sobes.tech AI
Answer from AI
ViewModel survives configuration changes (such as orientation or language change), preserving data. The lifecycle of ViewModel is tied to that of an Activity or Fragment, but it survives their recreation.
OnSavedInstanceState is part of the lifecycle of an Activity or Fragment. It is used to save a small amount of data before the component is destroyed (for example, due to low memory or configuration change). The data is stored in a Bundle.
Main differences:
- Lifecycle:
ViewModelsurvives configuration changes,OnSavedInstanceStatedoes not. - Data volume:
ViewModelis intended for storing data needed throughout the UI controller's lifecycle.OnSavedInstanceStateis for saving a small state. - Storage location:
ViewModelis stored in a special storage provided by Architecture Components.OnSavedInstanceStatesaves data in aBundle, which is restored upon UI controller creation. - Purpose:
ViewModelis meant for UI logic and data that survive configuration changes.OnSavedInstanceStateis for saving user interface state at the moment of component destruction.
| Criterion | ViewModel | OnSavedInstanceState |
|---|---|---|
| Survives configuration changes? | Yes | No |
| Typical data volume | Sufficiently large | Small |
| Storage mechanism | Special storage provided by Architecture Components | Bundle |
| Main purpose | UI logic and data | Saving user interface state |
Example of using ViewModel:
// MyViewModel.kt
class MyViewModel : ViewModel() {
val data: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
init {
// Load data
data.value = "Initial data"
}
}
Example of using OnSavedInstanceState:
// MyActivity.kt
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("savedText", textView.text.toString())
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState != null) {
val savedText = savedInstanceState.getString("savedText")
textView.text = savedText
}
}