Junior — Middle
How is the ViewModel used in Jetpack to manage UI state?
sobes.tech AI
Answer from AI
The ViewModel in Jetpack is used to store and manage UI-related data, preserving it during configuration changes (such as screen rotations). ViewModel separates UI logic from Activity or Fragment, making testing and maintenance easier.
Example usage:
class MyViewModel : ViewModel() {
private val _text = MutableLiveData<String>()
val text: LiveData<String> = _text
fun updateText(newText: String) {
_text.value = newText
}
}
// In Activity or Fragment
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
viewModel.text.observe(this) { updatedText ->
textView.text = updatedText
}
Thus, ViewModel stores data that survives UI recreation and provides it through LiveData for reactive UI updates.