UI State and Events
Use the helpers in ui:view-model to own editable state or share a source flow.
Collect them with collectAsStateWithLifecycle() in the ViewModel's state() method.
Editable State
Use mutableState for related screen fields:
kotlin1data class SignInUiState(2 val email: String = "",3 val isSubmitting: Boolean = false,4) : UiState56// Inside the ViewModel:7private val uiState = mutableState(SignInUiState())89private fun changeEmail(email: String) {10 uiState.update { current -> current.copy(email = email) }11}
update atomically transforms the current value. Keep the function free of side effects because concurrent updates can retry it.
Specify nullable types explicitly, such as mutableState<User?>(null).
An optional suspending factory receives the current value and returns its replacement:
kotlin1private val enabledState = mutableState(false) {2 tweaks.enabled(AppFeature.PLAYGROUND)3}
Automatic factory execution uses Dispatchers.Default and follows the sharing policy.
A factory result can overwrite edits made during loading. For editable data, load separately and merge the result with update.
MutableState.recreate() suspends, runs the factory in the caller's context, and replaces the value without resetting it first.
It works without subscribers; failures and cancellation propagate to the caller.
Observable State and Retry
Use observableState for an observer-backed stream. This example assumes an ObserveUser dependency and a User model:
kotlin1sealed interface ProfileUiState : UiState {2 data object Loading : ProfileUiState3 data class Content(val displayName: String) : ProfileUiState4 data object Error : ProfileUiState5}67// Inside the ViewModel:8private val profileState = observableState<ProfileUiState>(ProfileUiState.Loading) {9 observeUser(userId)10 .map<User, ProfileUiState> { user -> ProfileUiState.Content(user.displayName) }11 .catch { emit(ProfileUiState.Error) }12}1314@Composable15override fun state(): ProfileUiState {16 val state by profileState.collectAsStateWithLifecycle()17 return state18}1920private fun retry() {21 profileState.recreate()22}
Import map and catch from kotlinx.coroutines.flow.
ObservableState shares one upstream collection. Its recreate() requests an asynchronous reset and restart:
it waits for upstream cancellation cleanup, restores the initial value, then restarts when the sharing policy permits.
Handle recoverable failures inside the factory, as shown above.
An unhandled exception terminates the sharing coroutine; recreate() cannot restart it.
Both holders default to SharingStarted.WhileSubscribed(5.seconds) and retain their cached value when collection stops.
Events
Keep override val eventSink = createEventSink(::handleEvent) on the ViewModel and read viewModel.eventSink in the route.
Call it on the UI thread. Use immediate events for visible input, ThrottleFirst for repeated taps, and DebounceLatest for delayed effects.
See Screen Structure and Wiring for the complete pattern.