This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-21-stateflow-thread-confinement-standard

Kotlin Multiplatform 2.1 StateFlow Thread Confinement and Dispatcher Synchronization

Enforces strict thread confinement and atomic mutation boundaries for Coroutine StateFlow across Darwin Grand Central Dispatch and Android UI dispatchers in Kotlin Multiplatform 2.1. Eliminates memory tearing, re-entrancy deadlocks, and Swift/Kotlin memory model race conditions when bridge layers evaluate shared reactive state.

Prohibited Anti-Pattern: Cross-Thread MutableStateFlow Mutation and Unconfined Dispatcher Bridges Across Darwin GCD and Android Main

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform 2.1 StateFlow Thread Confinement and Dispatcher Synchronization - Enforces strict thread confinement and atomic mutation boundaries for Coroutine StateFlow across Darwin Grand Central Dispatch and Android UI dispatchers in Kotlin Multiplatform 2.1. Eliminates memory tearing, re-entrancy deadlocks, and Swift/Kotlin memory model race conditions when bridge layers evaluate shared reactive state.
globs: **/commonMain/**/*.kt, **/androidMain/**/*.kt, **/iosMain/**/*.kt, **/darwinMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-21-stateflow-thread-confinement-standard"
---

# Kotlin Multiplatform 2.1 StateFlow Thread Confinement and Dispatcher Synchronization

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Thread MutableStateFlow Mutation and Unconfined Dispatcher Bridges Across Darwin GCD and Android Main

## System Constraints
You are a Principal Mobile Architect enforcing Kotlin Multiplatform 2.1 Coroutine StateFlow Thread Confinement. Mandate invariants that eliminate thread safety violations, lock inversions, and memory tearing between Darwin GCD queues and Android Dispatchers.Main. Never permit direct exposed MutableStateFlow mutations across platform boundaries; enforce strict single-thread update loops via atomic updates and confined CoroutineScope lifecycles.

## Strict Guidelines
- Engineers MUST ALWAYS expose read-only StateFlow<T> interfaces across common boundaries, encapsulating MutableStateFlow<T> strictly within domain viewmodels or state containers.
- Engineers MUST ALWAYS mutate StateFlow values using atomic operators like MutableStateFlow.update { ... } or MutableStateFlow.compareAndSet to prevent check-then-act memory tearing across concurrent threads.
- Engineers MUST NOT collect or mutate shared StateFlow instances on unconfined dispatchers (such as Dispatchers.Unconfined or custom Darwin background GCD queues without serial confinement).
- Code SHOULD explicitly route UI-bound Darwin observation through a dedicated main-thread bridge or Darwin-safe wrapper (e.g., SKIE or explicit flow collectors confined to Dispatchers.Main.immediate).
- Services MUST ensure that state updates initiated from background I/O operations (Dispatchers.IO) switch execution context before mutating any StateFlow consumed synchronously by platform UI frameworks.
- Components NEVER execute blocking operations inside StateFlow subscription blocks, preventing lock inversions between Grand Central Dispatch main queues and Kotlin Coroutine dispatchers.

## Bad vs Good Implementations
### StateFlow Atomic Mutation and Platform Dispatcher Confinement

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Public MutableStateFlow permits concurrent Darwin and Android callers to read and write without isolation. Direct property assignment (uiState.value = ...) introduces race conditions and memory tearing. Launching on Dispatchers.IO and writing to a flow directly consumed by Darwin GCD bridges triggers lock inversions and unpredictable cross-thread scheduling overhead.
```kotlin
class ProfileViewModel : CoroutineScope {
    override val coroutineContext = Dispatchers.Default
    // ANTI-PATTERN: Public MutableStateFlow allows external platforms to mutate from any thread
    val uiState = MutableStateFlow(ProfileState.Initial)

    fun updateUsername(newName: String) {
        // ANTI-PATTERN: Direct property setter causes check-then-act memory tearing under concurrent calls
        val current = uiState.value
        if (current is ProfileState.Loaded) {
            uiState.value = current.copy(username = newName)
        }
    }

    fun loadData() {
        // ANTI-PATTERN: Mutating state directly from unconfined/IO threads without synchronization
        GlobalScope.launch(Dispatchers.IO) {
            val profile = repository.fetch()
            uiState.value = ProfileState.Loaded(profile.name)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates MutableStateFlow, ensures all updates use atomic CAS semantics via update { }, and bounds UI state emissions to Dispatchers.Main.immediate with lifecycle-managed cancellation. Darwin bridges receive safe, sequenced emissions without memory tearing or lock inversion across GCD runloops.
```kotlin
class ProfileViewModel(
    private val repository: ProfileRepository,
    private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main.immediate
) {
    private val scope = CoroutineScope(SupervisorJob() + mainDispatcher)

    // PROD INVARIANT: Mutable state is encapsulated; public consumer sees strictly immutable StateFlow
    private val _uiState = MutableStateFlow<ProfileState>(ProfileState.Initial)
    val uiState: StateFlow<ProfileState> = _uiState.asStateFlow()

    fun updateUsername(newName: String) {
        // PROD INVARIANT: update { } provides lock-free atomic compare-and-set
        _uiState.update { current ->
            when (current) {
                is ProfileState.Loaded -> current.copy(username = newName)
                else -> current
            }
        }
    }

    fun loadData() {
        scope.launch {
            // Background IO is isolated; state update guarantees main-thread confinement
            val profile = withContext(Dispatchers.IO) {
                repository.fetch()
            }
            _uiState.update { ProfileState.Loaded(profile.name) }
        }
    }

    fun clear() {
        scope.cancel()
    }
}
```

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: Kotlin Multiplatform 2.1 StateFlow Thread Confinement and Dispatcher Synchronization

Kotlin Multiplatform 2.1 StateFlow Thread Confinement and Dispatcher Synchronization defines an industrial-grade behavioral standard for mobile engineering. Enforces strict thread confinement and atomic mutation boundaries for Coroutine StateFlow across Darwin Grand Central Dispatch and Android UI dispatchers in Kotlin Multiplatform 2.1. Eliminates memory tearing, re-entrancy deadlocks, and Swift/Kotlin memory model race conditions when bridge layers evaluate shared reactive state. 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: Cross-Thread MutableStateFlow Mutation and Unconfined Dispatcher Bridges Across Darwin GCD and Android Main 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 DriftCross-Thread MutableStateFlow Mutation and Unconfined Dispatcher Bridges Across Darwin GCD and Android MainCritical
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 expose read-only StateFlow<T> interfaces across common boundaries, encapsulating MutableStateFlow<T> strictly within domain viewmodels or state containers.

Engineers MUST ALWAYS expose read-only StateFlow<T> interfaces across common boundaries, encapsulating MutableStateFlow<T> strictly within domain viewmodels or state containers.

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 ALWAYS mutate StateFlow values using atomic operators like MutableStateFlow.update { ... } or MutableStateFlow.compareAndSet to prevent check-then-act memory tearing across concurrent threads.

Engineers MUST ALWAYS mutate StateFlow values using atomic operators like MutableStateFlow.update { ... } or MutableStateFlow.compareAndSet to prevent check-then-act memory tearing across concurrent threads.

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

Engineers MUST NOT collect or mutate shared StateFlow instances on unconfined dispatchers (such as Dispatchers.Unconfined or custom Darwin background GCD queues without serial confinement).

Engineers MUST NOT collect or mutate shared StateFlow instances on unconfined dispatchers (such as Dispatchers.Unconfined or custom Darwin background GCD queues without serial confinement).

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

Code SHOULD explicitly route UI-bound Darwin observation through a dedicated main-thread bridge or Darwin-safe wrapper (e.g., SKIE or explicit flow collectors confined to Dispatchers.Main.immediate).

Code SHOULD explicitly route UI-bound Darwin observation through a dedicated main-thread bridge or Darwin-safe wrapper (e.g., SKIE or explicit flow collectors confined to Dispatchers.Main.immediate).

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

Services MUST ensure that state updates initiated from background I/O operations (Dispatchers.IO) switch execution context before mutating any StateFlow consumed synchronously by platform UI frameworks.

Services MUST ensure that state updates initiated from background I/O operations (Dispatchers.IO) switch execution context before mutating any StateFlow consumed synchronously by platform UI frameworks.

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.
6

Components NEVER execute blocking operations inside StateFlow subscription blocks, preventing lock inversions between Grand Central Dispatch main queues and Kotlin Coroutine dispatchers.

Components NEVER execute blocking operations inside StateFlow subscription blocks, preventing lock inversions between Grand Central Dispatch main queues and Kotlin Coroutine dispatchers.

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 Kotlin Multiplatform 2.1 StateFlow Thread Confinement and Dispatcher Synchronization critical for AI coding assistants?

Enforces strict thread confinement and atomic mutation boundaries for Coroutine StateFlow across Darwin Grand Central Dispatch and Android UI dispatchers in Kotlin Multiplatform 2.1. Eliminates memory tearing, re-entrancy deadlocks, and Swift/Kotlin memory model race conditions when bridge layers evaluate shared reactive state. 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 (Cross-Thread MutableStateFlow Mutation and Unconfined Dispatcher Bridges Across Darwin GCD and Android Main) 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

Kotlin