Skip to content

MVI / UDF

Recommended wiring: the field owns a TextFieldState, the Model observes it. A reducer's contract is (Model, Event) -> Model with an immutable Model. The text being typed must not round-trip through that Model, because a Model update that lands after the next key resets the field and drops the keystroke or misplaces a paste. Instead:

  • each field owns a TextFieldState (the editing buffer, on the Compose clock), held by your component, never by the Model;
  • the Model holds each field's text as a plain String plus its immutable FieldValidationState;
  • the reducer folds rules with the pure toFieldState(text, showError), exactly as before.

Text flows one way: field → textChanges() → dispatch → reduce. See the TextFieldState decision record for why, including a side-by-side demo of the old shape losing input.

Compose versions

TextFieldState exists on every Compose line yakcov ships (1.11+). Compose 1.13 deprecates the value/onValueChange text fields this replaces, so new forms should start here.

Setup in five steps

1. Model and events

The Model holds text as a String, not a TextFieldValue or a TextFieldState. The caret and selection live in the field's TextFieldState, so the Model doesn't need them.

// Plain top-level rule lists: shared by reduce() and any unit test, no Compose needed.
private val emailRules: List<ValueValidatorRule<String>> = listOf(Required, Email)
private val passwordRules: List<ValueValidatorRule<String>> = listOf(Required, MinLength(8))

// Every field is a val; FieldValidationState is @Immutable, so the Model is value-stable.
data class SignUpModel(
    val email: String = "",
    val emailState: FieldValidationState = FieldValidationState.Pristine,
    val password: String = "",
    val passwordState: FieldValidationState = FieldValidationState.Pristine,
    /** null = not attempted, true = accepted, false = blocked (errors surfaced). */
    val submitted: Boolean? = null,
    /** Monotonic submit counter — drives shake. A repeated invalid submit yields an
     *  EQUAL FieldValidationState, so a state diff alone can never re-fire the shake. */
    val submitAttempts: Int = 0,
) {
    /** Driven purely by severity (ignores showError) — live from the first frame. */
    val canSubmit: Boolean get() = listOf(emailState, passwordState).hasNoErrors()
}

/** Seed with rules pre-run (showError = false) so canSubmit is honest before any input. */
fun initialSignUpModel(): SignUpModel = SignUpModel(
    emailState = emailRules.toFieldState("", showError = false),
    passwordState = passwordRules.toFieldState("", showError = false),
)

sealed interface SignUpEvent {
    data class EmailChanged(val value: String) : SignUpEvent
    data object EmailFocusLost : SignUpEvent
    data class PasswordChanged(val value: String) : SignUpEvent
    data object PasswordFocusLost : SignUpEvent
    data object Submit : SignUpEvent
}

2. The reducer

Plain Kotlin, unit-testable, and unchanged from the pre-TextFieldState shape: a Changed event carries the new text and preserves showError, while FocusLost/Submit force it to true.

// THE pure core: (Model, Event) -> Model. No Compose, no coroutines, no IO.
// showError is threaded, not recomputed: Changed preserves it; FocusLost/Submit force it true.
fun reduce(model: SignUpModel, event: SignUpEvent): SignUpModel = when (event) {
    is SignUpEvent.EmailChanged -> model.copy(
        email = event.value,
        emailState = emailRules.toFieldState(event.value, model.emailState.showError),
        submitted = null,
    )
    SignUpEvent.EmailFocusLost -> model.copy(
        emailState = emailRules.toFieldState(model.email, showError = true),
    )
    is SignUpEvent.PasswordChanged -> model.copy(
        password = event.value,
        passwordState = passwordRules.toFieldState(event.value, model.passwordState.showError),
        submitted = null,
    )
    SignUpEvent.PasswordFocusLost -> model.copy(
        passwordState = passwordRules.toFieldState(model.password, showError = true),
    )
    SignUpEvent.Submit -> {
        // Surface errors on every field, then read validity off severity.
        val surfaced = model.copy(
            emailState = emailRules.toFieldState(model.email, showError = true),
            passwordState = passwordRules.toFieldState(model.password, showError = true),
            submitAttempts = model.submitAttempts + 1,
        )
        surfaced.copy(submitted = surfaced.canSubmit)
    }
}

3. The component owns the TextFieldStates and pipes their text into the store

This is the only new piece. Create one TextFieldState per field once, as a val on the component (a ViewModel, a Decompose component, a presenter). Then collect textChanges() into dispatch.

// The component: your ViewModel / Decompose component / presenter. It owns two things:
//  - the store (Model + dispatch) — the source of truth for everything except the keystrokes, and
//  - one TextFieldState per field — the editing buffer, owned by the field on the Compose clock.
// Text flows ONE way: field -> textChanges() -> dispatch -> reduce. Nothing ever writes the Model
// back into a field while the user types, so no keystroke or paste can be lost to a late update.
@Stable
class SignUpComponent(scope: CoroutineScope, initial: SignUpModel = initialSignUpModel()) {
    val email = TextFieldState(initial.email)
    val password = TextFieldState(initial.password)

    var model by mutableStateOf(initial)
        private set

    fun dispatch(event: SignUpEvent) {
        model = reduce(model, event)
    }

    init {
        // The whole hand-off. textChanges() emits plain Strings (current text first, then each
        // change) and ignores caret moves. In a ViewModel pass viewModelScope; in Decompose, the
        // component's lifecycle scope.
        scope.launch { email.textChanges().collect { dispatch(SignUpEvent.EmailChanged(it)) } }
        scope.launch { password.textChanges().collect { dispatch(SignUpEvent.PasswordChanged(it)) } }
    }
}

4. Bind the UI

Pass state = to the field. There is no value/onValueChange. Errors, supporting text, shake and focus-loss come from the Model, exactly as before.

@Composable
fun MviSignUpScreen() {
    // In an app this is your ViewModel / component; remembered here to keep the example standalone.
    val scope = rememberCoroutineScope()
    val component = remember { SignUpComponent(scope) }
    val model = component.model
    Column {
        OutlinedTextField(
            state = component.email, // the field owns the text — no value / onValueChange
            label = { Text("Email") },
            isError = model.emailState.isError,
            supportingText = model.emailState.supportingText(),
            lineLimits = TextFieldLineLimits.SingleLine,
            modifier = Modifier
                .fillMaxWidth()
                .onFocusCursorToEnd(state = component.email)
                .validationBehavior(
                    isError = model.emailState.isError,
                    shakeTrigger = model.submitAttempts,
                    onFocusLost = { component.dispatch(SignUpEvent.EmailFocusLost) },
                ),
        )
        OutlinedTextField(
            state = component.password,
            label = { Text("Password") },
            isError = model.passwordState.isError,
            supportingText = model.passwordState.supportingText(),
            lineLimits = TextFieldLineLimits.SingleLine,
            modifier = Modifier
                .fillMaxWidth()
                .validationBehavior(
                    isError = model.passwordState.isError,
                    shakeTrigger = model.submitAttempts,
                    onFocusLost = { component.dispatch(SignUpEvent.PasswordFocusLost) },
                ),
        )
        Button(
            onClick = { component.dispatch(SignUpEvent.Submit) },
            modifier = Modifier.fillMaxWidth(),
        ) { Text(if (model.canSubmit) "Create account" else "Fix errors to submit") }
        model.submitted?.let { Text(if (it) "Valid — proceeding" else "Fix the errors above") }
    }
}

5. Programmatic writes

Write to the TextFieldState, never to the Model. The write travels the same path as typing, and the Model catches up through textChanges(). setTextAndPlaceCursorAtEnd leaves the caret at the end, so there's no TextRange bookkeeping.

// Programmatic writes (suggestion pick, prefill, clear) go to the TextFieldState — the same path as
// typing — and reach the Model through textChanges(). The caret lands at the end.
fun SignUpComponent.prefillEmail(suggestion: String) = email.setTextAndPlaceCursorAtEnd(suggestion)

fun SignUpComponent.clearForm() {
    email.clearText()
    password.clearText()
}

When the reducer decides the text, for example a server load or a template fill, it can't touch the state because it's pure. Have it publish a one-shot, versioned seed, and apply that seed only when its version changes:

/** A reducer-owned, one-shot write request. The version makes each request distinct. */
data class Seed(val text: String, val version: Int)

@Composable
fun ProgrammaticWrites(state: TextFieldState, suggestions: List<String>, seed: Seed?) {
    // Reducer re-seed (server load, edit prefill): apply only when the version changes, so it can
    // never overwrite keystrokes the Model hasn't caught up with yet.
    LaunchedEffect(seed?.version) {
        if (seed != null) state.setTextAndPlaceCursorAtEnd(seed.text)
    }
    Column {
        OutlinedTextField(state = state)
        // Suggestion pick / preset fill: write the state at the event's source. Caret lands at the
        // end; the textChanges() collector carries the text to the Model.
        suggestions.forEach { s ->
            Button(onClick = { state.setTextAndPlaceCursorAtEnd(s) }) { Text(s) }
        }
        // Clear.
        Button(onClick = { state.clearText() }) { Text("Clear") }
    }
}

Rules of the road

  • Never put a TextFieldState in the Model. It's a mutable, reference-identity holder, so copy() aliases it and == becomes identity. It lives on the component, like any other UI-owned state.
  • Never echo the Model back into a field. For example, LaunchedEffect(model.email) { email.setText…(model.email) } compares the field against a Model that is one update behind and overwrites the newest keystrokes. Use the versioned seed above.
  • showError is threaded, not recomputed. Changed preserves it, and FocusLost and Submit force it to true. That gives "errors on blur or submit, never mid-keystroke".
  • canSubmit is honest from the first frame. Seed each field with rules.toFieldState("", showError = false), not FieldValidationState.Pristine. hasNoErrors() reads severity and ignores showError.
  • An action in the same frame as an edit: the Model catches up on the next snapshot apply, before the next frame, so a click sees the final text. If something can fire on the very frame of an edit, carry the text in the event: Submit(email = component.email.text.toString()).
  • Formatting goes in inputTransformation (to restrict input) and outputTransformation (to display it differently). Rules see the stored text: after the input transformation and before the output one. See the decision record.
  • Shake is driven by a monotonic counter, not a state diff. FieldValidationState equality includes its message, so a second invalid submit produces an == state, nothing recomposes, and a diff-driven shake would fire only once. Thread a submitAttempts counter in the Model and pass it as shakeTrigger. Modifier.validationBehavior(isError, shakeTrigger, onFocusLost) bundles that with focus-loss handling.
  • Screen readers get no signal from shake. It's a purely visual graphicsLayer translation, so if the form must be accessible, announce a blocked submit yourself.
  • Give disposable fields a stable key. The "don't shake on first frame" guard remembers the trigger it was born with. A field re-created after its subtree was disposed adopts the current counter as its baseline and swallows a shake that fell due while it was gone.
  • Cross-field rules (confirm-password and the like) are SAM lambdas that close over the Model. See custom rules.

Migrating from value / onValueChange

Before After
Model holds TextFieldValue (or String) and the field renders it Model holds String; the component holds a TextFieldState
OutlinedTextField(value = model.x, onValueChange = { dispatch(XChanged(it)) }) OutlinedTextField(state = component.x) plus x.textChanges().collect { dispatch(XChanged(it)) } on the component
XChanged(value: TextFieldValue), folding on value.text XChanged(text: String), folding on text; the reducer is otherwise unchanged
Prefill: TextFieldValue(text, TextRange(text.length)) TextFieldState(text) (caret at the end) or state.setTextAndPlaceCursorAtEnd(text)
Filter keystrokes in onValueChange and clamp the caret inputTransformation = …; the caret is handled for you
VisualTransformation outputTransformation = …
onFocusCursorToEnd(value, onValueChange) onFocusCursorToEnd(state = component.x)
validationBehavior(...) unchanged

Persistence & process death

FieldValidationState is @Immutable @Serializable: severity and showError persist, while the message (result) is @Transient and gets recomputed. The Model's Strings are the source of truth for restore. Persist them with each field's showError, then rehydrate by re-running the rules through toFieldState, and construct the component's TextFieldStates from the restored text (SignUpComponent(scope, initial = restored) does both). For cross-process JSON, add a kotlinx-serialization runtime and encode FieldValidationState directly. It persists Outcome by constant name.