Junior — Middle
What is the role of the ViewModel component in implementing the MVVM architecture?
sobes.tech AI
Answer from AI
The ViewModel in MVVM architecture is responsible for preparing and managing data for the user interface (View). It acts as an intermediary between the View and the data model, providing:
- Storage of UI state and data needed for display.
- Logic for transforming data from the model into a form suitable for display.
- Handling events and commands from the View.
The ViewModel does not contain direct references to the View, which facilitates testing and maintains separation of concerns.
An example in Kotlin for Android using LiveData:
class UserViewModel : ViewModel() {
private val userRepository = UserRepository()
val userData: LiveData<User> = userRepository.getUser()
fun refreshUser() {
userRepository.fetchUserFromNetwork()
}
}
Here, the ViewModel provides data via LiveData, and the View subscribes to this data and updates automatically.