Skip to content

Lesson 2 of 9 · 25m

State Hoisting, ViewModels, and Navigation Boundaries

Decide who owns UI state, expose events instead of leaking navigation, and keep composables testable as screens grow.

A screen becomes unmaintainable when every composable owns a little bit of truth and passes callbacks fourteen levels deep. Senior Android work is mostly ownership design: which layer owns the source of truth, which layer renders it, and which layer is allowed to move the user somewhere else. Get those boundaries right and Compose scales; get them wrong and even a settings screen becomes a plate of spaghetti.

Hoist state when reuse or correctness requires it

A stateless composable receives state and emits events:

@Composable
fun SearchField(
    query: String,
    onQueryChange: (String) -> Unit,
) {
    OutlinedTextField(value = query, onValueChange = onQueryChange)
}

The parent owns query, so previews, tests, restoration, and analytics do not depend on hidden widget internals. Keeping state low is convenient for purely local UI details like expansion state. Hoist it when other components need it, when it must survive recreation, or when business logic depends on it.

A ViewModel is a state owner, not a networking junk drawer

Expose one UI state flow and handle intent-like methods:

data class SearchUiState(
    val query: String = "",
    val results: List<Order> = emptyList(),
    val loading: Boolean = false,
    val error: String? = null,
)

class SearchViewModel(private val orders: OrderRepository) : ViewModel() {
    private val query = MutableStateFlow("")
    val uiState = query
        .debounce(300)
        .flatMapLatest { orders.search(it) }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SearchUiState(loading = true))

    fun onQueryChange(value: String) { query.value = value }
}

This pattern gives cancellation, backpressure behavior, and restoration boundaries a clear home. It also prevents the screen from juggling five separately stale flows.

Do not navigate from deep inside reusable UI

A row composable should emit onOrderClick(order.id). The screen or app layer decides what that means:

composable("orders") {
    OrderRoute(
        onOrderClick = { id -> navController.navigate("orders/$id") }
    )
}

Passing NavController into every leaf makes previews awkward and couples design components to route strings. Deep links, tablets, and nested navigation graphs become painful quickly.

Separate UI state from one-shot events

Snackbars, navigation, permission prompts, and share-sheet launches are events, not durable state. Represent them explicitly and consume them once:

sealed interface SearchEvent {
    data class ShowMessage(val text: String) : SearchEvent
    data class OpenOrder(val id: String) : SearchEvent
}

Do not stash a random Boolean in UI state and hope nobody sees it twice after rotation.

Field notes

  • Stateless components are easier to preview, screenshot-test, and reuse, but stateless purism can create callback noise; use judgment.
  • stateIn converts cold flows to shared state; choosing the wrong started strategy causes repeated network requests.
  • Process death can destroy the activity while retaining task state assumptions; test with the developer option "Don't keep activities" and process restoration.
  • Navigation arguments are strings by the time deep links get involved; validate and parse them at the boundary.
  • If a composable needs application scope just to show a toast, ownership is probably inverted.

Was this lesson helpful?

Sign in to rate