Skip to content

ViewModel

Recommended wiring: the field owns a TextFieldState, and the validator lives in the ViewModel and follows it. The VM holds one TextFieldState per field (the editing buffer) and a FieldValidator per field. textChanges() feeds the text to the validator, one way. FieldValidator has a plain constructor and is snapshot-state backed, so the form state survives configuration changes, submit() is unit-testable with no Compose UI, and composables reading field.state recompose automatically.

If your team's convention is strictly-immutable UI state, the second tab keeps a pure UiState of Strings and FieldValidationStates, fed the same way.

Don't render the text from VM state

OutlinedTextField(value = state.email, onValueChange = vm::onEmailChange) with a StateFlow + collectAsState() is the textbook skipped-input setup. collectAsState() delivers on a later frame, the field is reset to the stale text, and fast typing or a paste loses characters. Compose 1.13 deprecates that text-field shape. Let the field own the text, and have the VM observe it. See the decision record.

class SignUpViewModel : ViewModel() {
    // The FIELD owns the text: one TextFieldState per field, created once with the VM (so the
    // draft survives configuration changes). Never round-trip the text through the VM's state.
    val emailText = TextFieldState()
    val passwordText = TextFieldState()

    // FieldValidator has a plain (non-@Composable) constructor, so it is safe to own in a
    // ViewModel. Here it FOLLOWS the field's text and owns the validation state.
    val email = FieldValidator("", rules = listOf(Required, Email))
    val password = FieldValidator("", rules = listOf(Required, MinLength(8)))

    init {
        // One-way hand-off: text -> validator. textChanges() emits Strings and ignores caret moves.
        viewModelScope.launch { emailText.textChanges().collect(email::onValueChange) }
        viewModelScope.launch { passwordText.textChanges().collect(password::onValueChange) }
    }

    /** Form-level submit: shows errors on every field, true when all pass. Unit-testable without UI. */
    fun submit(): Boolean = listOf(email, password).validate()
}
@Composable
fun SignUpScreen(
    onSubmit: () -> Unit,
    viewModel: SignUpViewModel = viewModel { SignUpViewModel() },
) {
    Column {
        ValidatedField(viewModel.emailText, viewModel.email, label = "Email")
        ValidatedField(viewModel.passwordText, viewModel.password, label = "Password")
        Button(
            // submit() surfaces errors on every field and returns true only when all pass.
            onClick = { if (viewModel.submit()) onSubmit() },
            modifier = Modifier.fillMaxWidth(),
        ) { Text("Create account") }
    }
}

// The @Composable rendering helpers are called HERE, in composition — never in the
// ViewModel. isError is a plain property; supportingText() resolves string resources.
@Composable
private fun ValidatedField(text: TextFieldState, field: FieldValidator<String>, label: String) {
    OutlinedTextField(
        state = text, // the field owns the text — no value / onValueChange
        label = { Text(label) },
        isError = field.state.isError,
        supportingText = field.state.supportingText(),
        lineLimits = TextFieldLineLimits.SingleLine,
        modifier = Modifier
            .fillMaxWidth()
            .onFocusLost { field.onFocusLost() },
    )
}
private val emailRules = listOf(Required, Email)
private val passwordRules = listOf(Required, MinLength(8))

/** Text is a plain String snapshot of the field; the caret lives in the field's TextFieldState. */
data class SignUpUiState(
    val email: String = "",
    val emailState: FieldValidationState = FieldValidationState.Pristine,
    val password: String = "",
    val passwordState: FieldValidationState = FieldValidationState.Pristine,
) {
    val canSubmit: Boolean get() = listOf(emailState, passwordState).hasNoErrors()
}

class HoistedSignUpViewModel : ViewModel() {
    // The editing buffers — on the VM, NOT in SignUpUiState.
    val emailText = TextFieldState()
    val passwordText = TextFieldState()

    private val _state = MutableStateFlow(
        // Seed by folding the rules with showError = false so canSubmit is honest
        // before any input (a pristine required field must not look submittable).
        SignUpUiState(
            emailState = emailRules.toFieldState("", showError = false),
            passwordState = passwordRules.toFieldState("", showError = false),
        )
    )
    val state: StateFlow<SignUpUiState> = _state.asStateFlow()

    init {
        // field -> UiState, one way. The UiState never flows back into the field, so a state
        // update that lands a frame late can't overwrite (and drop) a newer keystroke.
        viewModelScope.launch { emailText.textChanges().collect(::onEmailChange) }
        viewModelScope.launch { passwordText.textChanges().collect(::onPasswordChange) }
    }

    private fun onEmailChange(value: String) = _state.update {
        // Recompute severity on every keystroke, but PRESERVE showError so no
        // error pops while the user is still typing.
        it.copy(email = value, emailState = emailRules.toFieldState(value, it.emailState.showError))
    }

    fun onEmailFocusLost() = _state.update {
        it.copy(emailState = emailRules.toFieldState(it.email, showError = true))
    }

    private fun onPasswordChange(value: String) = _state.update {
        it.copy(password = value, passwordState = passwordRules.toFieldState(value, it.passwordState.showError))
    }

    fun onPasswordFocusLost() = _state.update {
        it.copy(passwordState = passwordRules.toFieldState(it.password, showError = true))
    }

    /** Submit: force errors visible on all fields, then read validity off severity. */
    fun submit(): Boolean = _state.updateAndGet {
        it.copy(
            emailState = emailRules.toFieldState(it.email, showError = true),
            passwordState = passwordRules.toFieldState(it.password, showError = true),
        )
    }.canSubmit
}
@Composable
fun HoistedSignUpScreen(
    viewModel: HoistedSignUpViewModel = viewModel { HoistedSignUpViewModel() },
) {
    val state by viewModel.state.collectAsState()
    Column {
        OutlinedTextField(
            state = viewModel.emailText,
            label = { Text("Email") },
            isError = state.emailState.isError,
            supportingText = state.emailState.supportingText(),
            lineLimits = TextFieldLineLimits.SingleLine,
            modifier = Modifier
                .fillMaxWidth()
                .onFocusLost(viewModel::onEmailFocusLost),
        )
        OutlinedTextField(
            state = viewModel.passwordText,
            label = { Text("Password") },
            isError = state.passwordState.isError,
            supportingText = state.passwordState.supportingText(),
            lineLimits = TextFieldLineLimits.SingleLine,
            modifier = Modifier
                .fillMaxWidth()
                .onFocusLost(viewModel::onPasswordFocusLost),
        )
        Button(
            onClick = { viewModel.submit() },
            modifier = Modifier.fillMaxWidth(),
        ) { Text(if (state.canSubmit) "Create account" else "Fix errors to submit") }
    }
}

The @Composable boundary

The ViewModel never calls the @Composable rendering helpers. field.state.isError is a plain property the VM can read; supportingText() resolves string resources and must be called from the UI, in composition. Keep severity logic in the state holder and rendering in the composable.

Construct once, never copy

Construct a FieldValidator once and hold it (a VM/presenter field, DI, or remember). Don't construct it inside a recomposing body and don't copy it — both reset its validation state.

Formatting fields

Fields that reformat as the user types (currency, phone) use inputTransformation to restrict input and outputTransformation to change how it's displayed. The TextFieldState keeps the caret right, and the validator sees the stored text (after the input transformation, before the output one). There's no TextFieldValue or caret clamping to hand-roll. See Transformations.

Observability

FieldValidator takes an optional observer — a FieldValidatorObserver fired after every mutation commits (ValueChanged / Validated / Reset) with the post-mutation value + state. Handy for analytics, logging, or driving UI like the sample's live state-flow visualizer (StateFlowSample.kt). No event fires at construction; observers must not throw.

On restore-from-persistence, prefer FieldValidator(initial = restoredDraft, rules, initialValidate = true) over calling validate() — it re-runs the rules without emitting a Validated event an analytics tap would over-count.

Unit-testing presenters

If presenter/VM unit tests construct FieldValidator or read .value/.state, add org.jetbrains.compose:runtime to the test source set — it is not pulled in transitively.