ViewModel, Navigation and the Lifecycle

Article · 2:00

Where state survives a rotation, and how screens connect without Activities.

Rotating a device destroys and recreates the Activity. Any state held in the Activity or in remember is lost. A ViewModel survives that recreation, which is why it is the standard home for screen state and for anything in flight.

A ViewModel also brings a scope. viewModelScope is a CoroutineScope tied to the ViewModel's lifetime, so a coroutine launched in it is cancelled automatically when the screen goes away for good - structured concurrency from level three, applied to Android.

The modern pattern is unidirectional data flow. The ViewModel exposes a single immutable state object as a StateFlow; the UI collects it with collectAsStateWithLifecycle, which stops collecting when the screen is in the background; and the UI sends events back as plain function calls. State goes down, events go up, and there is exactly one source of truth. The sealed hierarchy from level two is how that state models loading, success and failure.

Navigation Compose connects screens inside the single Activity. A NavHost declares routes, each mapped to a composable, and a NavController moves between them while managing the back stack. Keep route arguments small - identifiers, not objects - and let each screen load what it needs.

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

// State modelled as a sealed hierarchy: invalid combinations cannot exist
sealed interface NotesUiState {
    data object Loading : NotesUiState
    data class Ready(val titles: List<String>) : NotesUiState
    data class Failed(val message: String) : NotesUiState
}

class NotesViewModel : ViewModel() {

    private val mutableState = MutableStateFlow<NotesUiState>(NotesUiState.Loading)
    val state: StateFlow<NotesUiState> = mutableState.asStateFlow()

    init {
        // viewModelScope is cancelled when the ViewModel is cleared
        viewModelScope.launch {
            mutableState.value = runCatching { loadTitles() }
                .fold(
                    onSuccess = { NotesUiState.Ready(it) },
                    onFailure = { NotesUiState.Failed(it.message ?: "unknown") },
                )
        }
    }

    // An event travelling up from the UI, as a plain function call
    fun retry() {
        mutableState.value = NotesUiState.Loading
    }

    private suspend fun loadTitles(): List<String> = listOf("Buy milk", "Call Ada")
}

Discussion

No questions on this topic yet. Sign in to ask the first one.