DEV Community

Cover image for Android app architecture: ViewModel, UDF and modules
duong vu
duong vu

Posted on Originally published at shippedcode.dev

Android app architecture: ViewModel, UDF and modules

Originally published at Shipped Code.

A screen usually starts with a ViewModel that loads a list, and 6 months later the same ViewModel formats dates, retries network calls and holds 3 booleans that contradict each other.

An Android app architecture that holds up after release needs few rules. Each screen gets one immutable UI state, exposed as a StateFlow by its ViewModel. User actions go up as function calls, and data sits behind a repository. Split into app, core and feature modules only when build time or team boundaries ask for it, with every dependency pointing one way.

data class ExpensesUiState(
    val rows: List<ExpenseRow> = emptyList(),
    val query: String = "",
    val isLoading: Boolean = false,
    val errorMessage: String? = null,
)

data class ExpenseRow(val id: Long, val title: String, val amount: String)
Enter fullscreen mode Exit fullscreen mode

TL;DR

  • One data class per screen, exposed as StateFlow<UiState>, collected with collectAsStateWithLifecycle().
  • Events are plain ViewModel functions. Never expose MutableStateFlow.
  • The ViewModel talks to a repository interface and never sees Retrofit or Room types.
  • State the user typed survives rotation for free, but survives process death only through SavedStateHandle.

What you'll learn

  • How to model one screen as a UI state, events and a ViewModel, and test it on the JVM.
  • Where the data layer starts and what the ViewModel must not know.
  • When splitting into app, core and feature modules pays off, and how Gradle keeps the graph one-way.

This post assumes Kotlin, Compose basics and some ViewModel use. Read through "Handling one-off events" for the screen pattern; the modules section matters once build time or team size becomes a problem.

I build Android apps such as PDFizi, a Jetpack Compose PDF reader and editor.

The UDF loop

Unidirectional data flow (UDF) means data moves in one direction around a loop. The screen renders state and reports what the user did. The ViewModel decides what that means, asks the repository for data, and publishes a new state. That is why the diagram below has events going up from the screen and state coming down from the ViewModel.

Vertical UDF loop: the Compose screen at the bottom sends events up to the ViewModel, the ViewModel calls refresh() on the repository at the top, the repository returns Flow<List<Expense>> down to the ViewModel, and the ViewModel sends StateFlow of UiState down to the screen

The point of the loop is that there is exactly one place where screen state changes. When a bug report says "the spinner never stops", you look in one class.

The example is smaller than a store app on purpose. It is an expense list split into 4 Gradle modules, built with Kotlin 2.4.21, AGP 9.5.2, Gradle 9.7.1, Compose BOM 2026.11.01 and Lifecycle 2.11.1, with minSdk 24, targetSdk 37 and compileSdk 37.1.

The screen reads only ExpensesUiState, and the ViewModel's public surface is uiState plus onQueryChange(), onRefresh() and onDelete(id). These are the pieces, followed by a diagram of how they call each other:

Component Responsibility
Expense (:core:model) The app's own model, with the amount stored in cents
ExpenseDto, ExpenseApi (:core:data) What the network returns; only the data layer sees these
ExpenseRepository + DefaultExpenseRepository Exposes Flow<List<Expense>>, refreshes and deletes
ExpensesUiState, ExpenseRow Everything the screen draws, already formatted
ExpensesViewModel Combines data and screen state, handles events
ExpensesRoute, ExpensesScreen Collects state, renders it, forwards clicks
ExpensesApp (:app) Builds the repository and wires it in

Component relationships: ExpensesApp builds the repository and passes it to ExpensesViewModel; ExpensesRoute/ExpensesScreen calls the ViewModel's event functions and gets StateFlow<ExpensesUiState> back; the ViewModel calls refresh() and delete() and collects expenses from ExpenseRepository; the repository calls fetchExpenses() on ExpenseApi, gets List<ExpenseDto> and maps it to Expense

Read the diagram from the ViewModel outwards: the screen only calls event functions and receives state, the repository is the only thing the ViewModel calls down into, and ExpenseApi and ExpenseDto stay hidden behind the repository.

One UI state class per screen

The UI state is one immutable object that holds everything the screen needs to draw. You can model loading and errors as fields of a data class (as above) or as a sealed interface with Loading, Success and Error cases.

I pick the data class for list screens. A list often has to show old rows, a refresh spinner and an error message at the same time, and a sealed interface forces you to choose one. A sealed interface fits better when the states really exclude each other, like a detail screen that has nothing to show until the first load finishes.

The ViewModel builds the state by combining the repository's data with the small pieces of state the screen owns. Imports are omitted in the Kotlin snippets.

class ExpensesViewModel(
    private val repository: ExpenseRepository,
    private val savedState: SavedStateHandle,
) : ViewModel() {
    private val query = savedState.getStateFlow(KEY_QUERY, "")
    private val status = MutableStateFlow(LoadStatus())

    val uiState: StateFlow<ExpensesUiState> =
        combine(repository.expenses, query, status) { expenses, q, s ->
            ExpensesUiState(
                rows = expenses.filter { it.title.contains(q, ignoreCase = true) }.map { it.toRow() },
                query = q,
                isLoading = s.isLoading,
                errorMessage = s.errorMessage,
            )
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ExpensesUiState(isLoading = true))
}

private data class LoadStatus(val isLoading: Boolean = false, val errorMessage: String? = null)

private fun Expense.toRow() =
    ExpenseRow(id, title, String.format(Locale.US, "$%.2f", amountCents / 100.0))
Enter fullscreen mode Exit fullscreen mode

stateIn(..., WhileSubscribed(5_000)) keeps the upstream flows running while the screen is collecting and for 5 seconds after it stops. A rotation takes well under 5 seconds, so the combine is not restarted on every configuration change. Formatting the amount here, and not in the composable, keeps the screen dumb and makes the formatting testable on the JVM.

On the Compose side, collectAsStateWithLifecycle() from lifecycle-runtime-compose stops collecting when the app goes to the background, which plain collectAsState() does not do.

@Composable
fun ExpensesRoute(viewModel: ExpensesViewModel) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    ExpensesScreen(
        state = state,
        onQueryChange = viewModel::onQueryChange,
        onRefresh = viewModel::onRefresh,
        onDelete = viewModel::onDelete,
    )
}
Enter fullscreen mode Exit fullscreen mode

ExpensesScreen itself takes the state and 3 lambdas, so a preview or a UI test can call it without a ViewModel at all.

How to send events to the ViewModel

There are 2 common ways to send events up. One is a single onEvent(event: ExpensesEvent) with a sealed class of events, the style MVI libraries such as Orbit and Mavericks use. The other is one plain function per action.

    init { refresh() }

    fun onQueryChange(value: String) { savedState[KEY_QUERY] = value }
    fun onRefresh() = refresh()
    fun onDelete(id: Long) { viewModelScope.launch { repository.delete(id) } }

    private fun refresh() {
        viewModelScope.launch {
            status.value = LoadStatus(isLoading = true)
            status.value = try {
                repository.refresh()
                LoadStatus()
            } catch (e: IOException) {
                LoadStatus(errorMessage = "Couldn't refresh. Tap Refresh to retry.")
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

I recommend plain functions for most screens. "Find usages" works per action, the composable passes viewModel::onRefresh directly, and you skip a when that only dispatches. A single onEvent starts to pay off when you log or replay every event, or when a screen has so many actions that the parameter list of the composable gets silly.

Notice that a failed refresh only changes status. The rows still come from the repository, so the user keeps seeing the last list with an error under the search field. A unit test confirms that the rows survive a failed refresh.

ExpensesViewModelTest > failedRefreshKeepsRowsAndShowsError STANDARD_OUT
    rows=4 isLoading=false error=Couldn't refresh. Tap Refresh to retry.
Enter fullscreen mode Exit fullscreen mode

Warning: expose StateFlow, never MutableStateFlow. If uiState is mutable from outside, any composable can write viewModel.uiState.value = ..., and the one-place-for-state-changes rule is gone. Keep the mutable flows private and expose a read-only flow, built with stateIn as above or with asStateFlow().

Where the data layer starts

The data layer starts at the repository interface. Above it, the ViewModel knows Expense and Flow. Below it are DTOs, Retrofit services, Room entities and caching.

interface ExpenseRepository {
    val expenses: Flow<List<Expense>>
    suspend fun refresh()
    suspend fun delete(id: Long)
}

class DefaultExpenseRepository(private val api: ExpenseApi) : ExpenseRepository {
    private val cache = MutableStateFlow<List<Expense>>(emptyList())
    override val expenses: Flow<List<Expense>> = cache.asStateFlow()

    override suspend fun refresh() {
        cache.value = api.fetchExpenses().map { it.toModel() }
    }

    override suspend fun delete(id: Long) {
        cache.update { list -> list.filterNot { it.id == id } }
    }
}

private fun ExpenseDto.toModel() =
    Expense(id = id, title = note, amountCents = amount.toBigDecimal().movePointRight(2).toLong())
Enter fullscreen mode Exit fullscreen mode

The API sends the amount as a string such as "3.50" and calls the title note. The mapping sits in one private function, so a renamed JSON field changes one line and no ViewModel. In a real app ExpenseApi would be a Retrofit interface and the in-memory cache would be a Room table (Room gets its own post later in this series).

The repository's shape also follows from the backend's API contract, which is where an Android app and its server have to agree. The system design post for app developers covers that side.

Should there be a use-case layer between ViewModel and repository? For simple screens I call the repository directly. I add a use case when the same logic is shared by 2 or more ViewModels, or when it is complex enough that I want to test it on its own. A GetExpensesUseCase that only forwards one call is an extra file to maintain, with no logic of its own.

The ViewModel gets its repository through the constructor. Here ExpensesApp builds it by hand and passes it to a viewModelFactory. A DI framework like Hilt would generate that wiring, and Hilt gets its own post later in the series.

Handling one-off events

Navigation after a save, or a snackbar, does not fit neatly into state, because it should happen once. The simplest approach that survives rotation is to keep the event in the state, for example a snackbarMessage: String? field, and let the screen call something like onSnackbarShown() after it displays it, so the ViewModel clears it. (errorMessage above is different: it is meant to stay visible until the next refresh.) Channels and SharedFlow are the other options, each with its own way of losing an event, and a later post compares them.

When to split into feature modules (advanced)

Everything above works in a single app module. Modularization pays off in 2 cases: Gradle can then skip recompiling modules you didn't touch, or teams can own separate parts of the code with clear boundaries. If neither applies yet, the extra build files cost more than they give back. The modularization guide lists the patterns in more depth, and the Now in Android sample shows them at a larger scale.

The example uses 4 modules, and every arrow points down.

Module graph: :app depends on :feature:expenses and :core:data; :feature:expenses depends on :core:data; :core:data depends on :core:model

:core:model and :core:data are plain Kotlin/JVM modules, not Android libraries, because nothing in them needs Android. That choice enforces the direction for you. When I added a dependency from :core:data to :feature:expenses, Gradle refused to build, though not with a friendly message.

> Could not resolve project ':feature:expenses'.
     Required by:
         project ':core:data'
      > ... However we cannot choose between the following variants of project ':feature:expenses':
          - debugApiElements
          - releaseApiElements
Enter fullscreen mode Exit fullscreen mode

A JVM module cannot consume an Android library at all. A real cycle between 2 modules of the same kind gets a clearer message, as I saw when I made :core:model depend on :core:data.

* What went wrong:
Circular dependency between the following tasks:
:core:data:classes
\--- :core:data:compileJava
     +--- :core:data:compileKotlin
     |    \--- :core:model:jar
...
Enter fullscreen mode Exit fullscreen mode

A data layer that uses Room or Context has to be an Android library, so you lose this guard there. In that case the dependency graph is the thing to review in pull requests.

The other surprise is that implementation dependencies are not passed on. The feature module declares lifecycle-viewmodel-compose, yet MainActivity in :app failed to compile with Unresolved reference 'viewModel' until :app declared that library too. This is intended, since it keeps each module's classpath small. In practice it means :app lists what it uses, or the feature module exposes an entry point that hides the ViewModel creation.

For these versions, 2 details of the build setup are worth knowing. AGP 9 compiles Kotlin itself, so Android modules apply only com.android.library (or application) and the Compose compiler plugin, with no kotlin-android plugin. And Compose BOM 2026.11.01 requires compileSdk 37.1, which the build reports as a failed AAR metadata check. The minor API level is set like this.

android {
    namespace = "dev.shippedcode.feature.expenses"
    compileSdk {
        version = release(37) { minorApiLevel = 1 }
    }
    defaultConfig { minSdk = 24 }
    buildFeatures { compose = true }
}
Enter fullscreen mode Exit fullscreen mode

Common traps

Rotation is not process death. I typed "co" into the search field on an API 37 emulator, rotated, then sent the app to the background and killed its process with adb shell am kill. With the query in a plain MutableStateFlow(""), rotation kept "co", but after the process came back the field was empty and all 4 rows were back. Moving the query into SavedStateHandle (the version shown above) kept it through both.

In the log below, the activity is recreated 3 times (rotate, rotate back, new process), but the ViewModel's init runs again only in the new process.

6418 D ExpensesVM: Activity onCreate restored=false
6418 D ExpensesVM: init 2973980
6418 D ExpensesVM: Activity onCreate restored=true
6418 D ExpensesVM: Activity onCreate restored=true
6602 D ExpensesVM: Activity onCreate restored=true
6602 D ExpensesVM: init 244388133
Enter fullscreen mode Exit fullscreen mode

The first column is the process id, and it changes only after the kill.

Put only small, user-entered state in SavedStateHandle (a query, a selected tab, an id). The list itself should be reloaded from the repository.

Warning: init { refresh() } runs once per ViewModel instance, which is what you want only if the instance is created by viewModel() or a DI helper. When I created it with remember { ExpensesViewModel(...) } instead, every rotation logged a new init, refreshed again and lost the query. remember does not survive a configuration change, and a ViewModel built that way is never cleared by the system.

Reading uiState.value in a test without collecting it. Because of WhileSubscribed, the combine only runs while someone collects. A test that waited for the refresh and then read the value got the initial state.

no collector: rows=0 isLoading=true
Enter fullscreen mode Exit fullscreen mode

Start a collector first with backgroundScope.launch { vm.uiState.collect {} }, then the same test sees 4 rows. Tests also need Dispatchers.setMain(StandardTestDispatcher()), because viewModelScope runs on the main dispatcher, which doesn't exist on the JVM.

android.util.Log in a ViewModel breaks JVM unit tests. All 3 tests failed with Method d in android.util.Log not mocked because of one Log.d call in init (the one that printed the init lines in the log above). Setting testOptions { unitTests.isReturnDefaultValues = true } makes them pass. Keeping Android calls out of the ViewModel works too, and is the better long-term fix.

It is time to change the structure when a ViewModel imports Retrofit or Room types, or when the screen needs 3 booleans to know what to draw. The same goes for a fix in one feature that forces a rebuild of every module, and for 2 ViewModels that copy the same block of logic, which is the moment to add a use case. A long ViewModel on its own tells you less than any of these.

Next step

The screen in this post recomposes every time uiState emits. The next post in the series looks at what Compose actually redraws when that happens, and how to keep a long list from doing more work than it should.

Where this structure sits among other mobile decisions, including native versus Flutter, is the subject of the mobile pillar post.

More posts in this area are under Android development.

Top comments (0)