Junior
Tell me about the MVVM pattern.
sobes.tech AI
Answer from AI
Model-View-ViewModel (MVVM) is an architectural pattern that separates the user interface (View) from business logic (Model) with the help of an intermediary — the ViewModel.
- Model: Represents the data and business logic of the application. Contains no UI-specific logic.
- View: Displays data from the ViewModel and sends user actions (e.g., button presses) to the ViewModel. Contains no business logic, only presentation logic.
- ViewModel: Acts as a link. Provides data from the Model to the View in a format suitable for display and handles requests from the View, updating the Model. Contains presentation logic but does not manipulate the View directly. Often uses LiveData or StateFlow for reactive updates.
Advantages:
- Separation of concerns: Improves readability and maintainability of the code.
- Testability: ViewModel is easy to test in isolation since it does not depend on the Android API.
- Lifecycle awareness: ViewModel survives configuration changes (e.g., screen rotation) and avoids re-fetching data.
- Enhanced modularity.
Example structure:
// Model (repository for example)
class UserRepository {
fun getUsers(): List<User> {
// ... logic to fetch users ...
return listOf(User("Alice"), User("Bob"))
}
}
// ViewModel
class UserViewModel(private val repository: UserRepository) : ViewModel() {
private val _users = MutableLiveData<List<User>>()
val users: LiveData<List<User>> = _users
init {
loadUsers()
}
private fun loadUsers() {
_users.value = repository.getUsers()
}
}
// View (Fragment/Activity)
class UserFragment : Fragment() {
private val viewModel: UserViewModel by viewModels() // Using Android KTX delegate
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.users.observe(viewLifecycleOwner) { userList ->
// Update UI (e.g., RecyclerView adapter)
updateUI(userList)
}
}
private fun updateUI(userList: List<User>) {
// Logic to update TextView, RecyclerView, etc.
}
}