Junior — Middle
What is the role of ViewModel in implementing architectural patterns in applications?
sobes.tech AI
Answer from AI
ViewModel in architectural patterns such as MVVM (Model-View-ViewModel) is responsible for managing data and presentation logic, separating the UI (View) from business logic and data (Model). This allows the UI to be simpler and more reactive, as well as maintaining state during configuration changes, such as screen rotation.
Main tasks of ViewModel:
- Storing and preparing data for display.
- Handling user actions and interacting with the model.
- Preserving UI state across activity or fragment recreations.
Example in Kotlin using LiveData:
class UserViewModel : ViewModel() {
private val userRepository = UserRepository()
val userData: LiveData<User> = userRepository.getUserData()
fun refreshUser() {
userRepository.fetchUserFromNetwork()
}
}
Here, the ViewModel provides data for the View and manages their updates, independent of the UI components' lifecycle.