Junior — Middle
How can you ensure the preservation of screen data when changing device configuration using ViewModel?
sobes.tech AI
Answer from AI
The ViewModel in Android is designed to store and manage UI data, preserving it during configuration changes (e.g., screen rotation).
To ensure data preservation:
- Create a ViewModel class where screen data will be stored.
- Use ViewModelProvider to obtain an instance of ViewModel in an Activity or Fragment.
- When the configuration changes, the system recreates the Activity/Fragment, but the ViewModel persists and provides the same data.
Example:
class MyViewModel : ViewModel() {
val data = MutableLiveData<String>()
}
// In Activity or Fragment
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
// Use viewModel.data to display and update the UI
Thus, data is not lost when the UI is recreated, as the ViewModel lives longer and maintains the state.