Sobes.tech
Junior — Middle

How to implement the MVVM pattern in applications using Jetpack Compose for UI

sobes.tech AI

Answer from AI

In Jetpack Compose, the MVVM pattern is implemented through the separation of:

  • Model — business logic and data.
  • ViewModel — holds UI state and handles interaction logic.
  • View (Compose UI) — displays data and responds to state changes.

Example:

class MyViewModel : ViewModel() {
    // UI state, for example, a text field
    var text by mutableStateOf("")
        private set

    fun onTextChanged(newText: String) {
        text = newText
    }
}

@Composable
fun MyScreen(viewModel: MyViewModel = viewModel()) {
    val text = viewModel.text
    TextField(
        value = text,
        onValueChange = { viewModel.onTextChanged(it) },
        label = { Text("Enter text") }
    )
}

Here, the ViewModel contains the state and methods to modify it. The Compose UI subscribes to the state via mutableStateOf, automatically updating upon changes.

This approach ensures a clean separation of concerns and simplifies testing.

How to implement the MVVM pattern in applications… - sobes.tech