This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-compose-state-mutation-boundary

Enforce Target-Native Main Dispatcher Boundaries for Compose Multiplatform State Mutations

Ensures all shared Kotlin Multiplatform (KMP) StateFlow, SharedFlow, and Compose runtime state mutations execute strictly on Dispatchers.Main.immediate. Cross-thread state updates originating from background dispatchers bypass UIKit and Android Choreographer synchronizations, inducing UI race conditions, deadlocks, and missed recomposition frames.

Prohibited Anti-Pattern: Mutating Shared ViewState on Unconfined or Worker Dispatchers Triggering Multiplatform UI Desynchronization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Enforce Target-Native Main Dispatcher Boundaries for Compose Multiplatform State Mutations - Ensures all shared Kotlin Multiplatform (KMP) StateFlow, SharedFlow, and Compose runtime state mutations execute strictly on Dispatchers.Main.immediate. Cross-thread state updates originating from background dispatchers bypass UIKit and Android Choreographer synchronizations, inducing UI race conditions, deadlocks, and missed recomposition frames.
globs: **/commonMain/**/viewmodel/**/*.kt, **/commonMain/**/presentation/**/*.kt, **/commonMain/**/ui/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-compose-state-mutation-boundary"
---

# Enforce Target-Native Main Dispatcher Boundaries for Compose Multiplatform State Mutations

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Mutating Shared ViewState on Unconfined or Worker Dispatchers Triggering Multiplatform UI Desynchronization

## System Constraints
You are a Principal Mobile Architect enforcing Kotlin Multiplatform Compose State Lifecycle Mutation Boundaries. Mandate that all state container mutations, Flow collections for presentation, and Compose snapshot transitions are strictly confined to Dispatchers.Main.immediate. Reject any ViewModel implementation that directly executes UI state updates inside non-main coroutine contexts or relies on unconfined platform dispatchers.

## Strict Guidelines
- Engineers MUST ALWAYS trigger MutableStateFlow mutations and snapshot state writes on Dispatchers.Main.immediate to guarantee lock-free synchronization with platform render cycles.
- Engineers MUST NOT switch ViewModel root scopes to Dispatchers.IO or Dispatchers.Default; offload computational or I/O workloads using granular `withContext(Dispatchers.IO)` calls within main-scoped coroutines.
- Code SHOULD configure `SharingStarted.WhileSubscribed(stopTimeoutMillis = 5_000)` on all `stateIn` operators to prevent background state emissions during UI lifecycle detachment.
- Services MUST return pure immutable domain models or raw data flows, leaving state reduction and dispatcher confinement exclusively to presentation layer view models.
- Components NEVER collect state flows inside multiplatform composables using unconfined dispatchers; collection MUST bind to the composition lifecycle via `collectAsStateWithLifecycle()`.

## Bad vs Good Implementations
### Shared ViewModel State Mutation Boundary Enforcement

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mutating _uiState within Dispatchers.IO violates Compose Multiplatform thread-affinity rules. On iOS, updating state off the main thread risks race conditions in the Skiko/UIKit render pipeline; on Android, it leads to dropped frames and snapshot state collision exceptions.
```kotlin
class UserProfileViewModel(
    private val userRepository: UserRepository
) : ViewModel() {
    private val _uiState = MutableStateFlow<ProfileUiState>(ProfileUiState.Loading)
    val uiState: StateFlow<ProfileUiState> = _uiState.asStateFlow()

    fun loadProfile(userId: String) {
        // VIOLATION: Launching on Dispatchers.IO causes state mutations off the main thread,
        // causing snapshot conflicts and race conditions on iOS and Android Compose runtimes.
        viewModelScope.launch(Dispatchers.IO) {
            val user = userRepository.fetchUser(userId)
            _uiState.update { ProfileUiState.Success(user) }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The coroutine starts and finishes state updates on Dispatchers.Main.immediate. The blocking I/O operation is isolated within a `withContext(ioDispatcher)` block, safely suspending and resuming back to the target-native UI dispatcher before mutating state.
```kotlin
class UserProfileViewModel(
    private val userRepository: UserRepository,
    private val mainImmediateDispatcher: CoroutineDispatcher = Dispatchers.Main.immediate,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : ViewModel() {
    private val _uiState = MutableStateFlow<ProfileUiState>(ProfileUiState.Loading)
    val uiState: StateFlow<ProfileUiState> = _uiState.asStateFlow()

    fun loadProfile(userId: String) {
        // COMPLIANT: Root coroutine retains Dispatchers.Main.immediate affinity.
        viewModelScope.launch(mainImmediateDispatcher) {
            _uiState.update { ProfileUiState.Loading }
            
            // Boundary: I/O execution is scoped down, then resumed on Main.immediate.
            val result = runCatching {
                withContext(ioDispatcher) {
                    userRepository.fetchUser(userId)
                }
            }
            
            _uiState.update {
                result.fold(
                    onSuccess = { ProfileUiState.Success(it) },
                    onFailure = { ProfileUiState.Error(it.message ?: "Unknown error") }
                )
            }
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Enforce Target-Native Main Dispatcher Boundaries for Compose Multiplatform State Mutations

Enforce Target-Native Main Dispatcher Boundaries for Compose Multiplatform State Mutations defines an industrial-grade behavioral standard for mobile engineering. Ensures all shared Kotlin Multiplatform (KMP) StateFlow, SharedFlow, and Compose runtime state mutations execute strictly on Dispatchers.Main.immediate. Cross-thread state updates originating from background dispatchers bypass UIKit and Android Choreographer synchronizations, inducing UI race conditions, deadlocks, and missed recomposition frames. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Mutating Shared ViewState on Unconfined or Worker Dispatchers Triggering Multiplatform UI Desynchronization Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftMutating Shared ViewState on Unconfined or Worker Dispatchers Triggering Multiplatform UI DesynchronizationCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS trigger MutableStateFlow mutations and snapshot state writes on Dispatchers.Main.immediate to guarantee lock-free synchronization with platform render cycles.

Engineers MUST ALWAYS trigger MutableStateFlow mutations and snapshot state writes on Dispatchers.Main.immediate to guarantee lock-free synchronization with platform render cycles.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT switch ViewModel root scopes to Dispatchers.IO or Dispatchers.Default

Engineers MUST NOT switch ViewModel root scopes to Dispatchers.IO or Dispatchers.Default; offload computational or I/O workloads using granular `withContext(Dispatchers.IO)` calls within main-scoped coroutines.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code SHOULD configure `SharingStarted.WhileSubscribed(stopTimeoutMillis = 5_000)` on all `stateIn` operators to prevent background state emissions during UI lifecycle detachment.

Code SHOULD configure `SharingStarted.WhileSubscribed(stopTimeoutMillis = 5_000)` on all `stateIn` operators to prevent background state emissions during UI lifecycle detachment.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST return pure immutable domain models or raw data flows, leaving state reduction and dispatcher confinement exclusively to presentation layer view models.

Services MUST return pure immutable domain models or raw data flows, leaving state reduction and dispatcher confinement exclusively to presentation layer view models.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER collect state flows inside multiplatform composables using unconfined dispatchers

Components NEVER collect state flows inside multiplatform composables using unconfined dispatchers; collection MUST bind to the composition lifecycle via `collectAsStateWithLifecycle()`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Enforce Target-Native Main Dispatcher Boundaries for Compose Multiplatform State Mutations critical for AI coding assistants?

Ensures all shared Kotlin Multiplatform (KMP) StateFlow, SharedFlow, and Compose runtime state mutations execute strictly on Dispatchers.Main.immediate. Cross-thread state updates originating from background dispatchers bypass UIKit and Android Choreographer synchronizations, inducing UI race conditions, deadlocks, and missed recomposition frames. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Mutating Shared ViewState on Unconfined or Worker Dispatchers Triggering Multiplatform UI Desynchronization) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Enforce