MVVM Architecture in Android with Kotlin and Compose

Short answer: MVVM (Model-View-ViewModel) splits your Android app into three parts. The Model holds data and business logic, the ViewModel exposes screen state and survives configuration changes, and the View (your composable or Activity) only displays that state and sends user events back. Google recommends this separation in its official architecture guidance.

This tutorial builds a small MVVM app in Kotlin and Jetpack Compose that loads a list of users and handles loading, success and error states.

MVVM in three parts

  • Model: data classes and a repository that gets data from a network, database or fake source.
  • ViewModel: holds UI state in a StateFlow, runs work in viewModelScope and never references views or Context.
  • View: observes the state and draws the screen. It forwards clicks and input to the ViewModel.

Why use it? Your UI logic becomes easy to test, the screen survives rotation without reloading, and each layer has one job.

Step 1: The model and repository

data class User(val id: Int, val name: String)

interface UserRepository {
    suspend fun getUsers(): List<User>
}

class FakeUserRepository : UserRepository {
    override suspend fun getUsers(): List<User> {
        delay(1000) // pretend this is a network call
        return listOf(
            User(1, "Asha"),
            User(2, "Ravi"),
            User(3, "Meera")
        )
    }
}

Using an interface lets you swap the fake for a real Retrofit or Room implementation later, and use a fake in tests.

Step 2: Define the UI state

sealed interface UsersUiState {
    data object Loading : UsersUiState
    data class Success(val users: List<User>) : UsersUiState
    data class Error(val message: String) : UsersUiState
}

data object needs Kotlin 1.9 or newer. On older versions, use object. A sealed type makes the screen handle every state, and the compiler warns you if you forget one.

Step 3: Create the ViewModel

class UsersViewModel(
    private val repository: UserRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow<UsersUiState>(UsersUiState.Loading)
    val uiState: StateFlow<UsersUiState> = _uiState.asStateFlow()

    init {
        loadUsers()
    }

    fun loadUsers() {
        viewModelScope.launch {
            _uiState.value = UsersUiState.Loading
            _uiState.value = try {
                UsersUiState.Success(repository.getUsers())
            } catch (e: Exception) {
                UsersUiState.Error(e.message ?: "Something went wrong")
            }
        }
    }
}

The ViewModel keeps a private mutable flow and exposes a read-only StateFlow. Only the ViewModel can change the state, which is the key idea behind unidirectional data flow.

Step 4: Build the screen

@Composable
fun UsersScreen(viewModel: UsersViewModel) {
    val state by viewModel.uiState.collectAsState()

    when (val current = state) {
        UsersUiState.Loading -> {
            Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                CircularProgressIndicator()
            }
        }
        is UsersUiState.Success -> {
            LazyColumn(contentPadding = PaddingValues(16.dp)) {
                items(current.users, key = { it.id }) { user ->
                    Text(
                        text = user.name,
                        modifier = Modifier.padding(vertical = 8.dp),
                        style = MaterialTheme.typography.titleMedium
                    )
                }
            }
        }
        is UsersUiState.Error -> {
            Column(
                Modifier.fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(current.message)
                Button(onClick = viewModel::loadUsers) { Text("Retry") }
            }
        }
    }
}

In production apps, prefer collectAsStateWithLifecycle() from the lifecycle-runtime-compose library. It stops collecting when the screen is not visible.

Step 5: Provide the ViewModel in MainActivity

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                val viewModel = viewModel<UsersViewModel>(
                    factory = viewModelFactory {
                        initializer { UsersViewModel(FakeUserRepository()) }
                    }
                )
                UsersScreen(viewModel)
            }
        }
    }
}

The factory is needed because the ViewModel takes a constructor parameter. With dependency injection you can remove it. See our Dagger Hilt tutorial to inject the repository automatically.

Common MVVM mistakes

  • Passing Context or Views into the ViewModel. This causes memory leaks and breaks testing.
  • Exposing MutableStateFlow publicly. Expose an immutable StateFlow so only the ViewModel changes state.
  • Putting business logic in the composable. Keep it in the ViewModel or repository.
  • Using several flows for one screen. A single UI state object is easier to reason about and test.

FAQ

What is MVVM in Android?

MVVM is an architecture pattern that separates data (Model), screen logic and state (ViewModel) and UI (View), so each part can change and be tested on its own.

What is the difference between MVVM and MVP?

In MVP the Presenter holds a reference to the View and updates it directly. In MVVM the ViewModel exposes state and the View observes it, so the ViewModel does not know about the View.

Do I need Hilt for MVVM?

No. Hilt only helps create and inject dependencies. MVVM works with manual factories as shown above.

Should I use LiveData or StateFlow?

For new Compose apps, StateFlow is the usual choice. LiveData still works and is common in older View-based apps.

More guides: Jetpack Compose tutorials and scrollable Column examples.