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

Kotlin/Native StateFlow to Swift Actor Dispatcher & Immutability Fence Architecture

Enforces strict dispatcher confinement and deep value immutability when exporting Kotlin Coroutines StateFlow primitives across the Darwin Objective-C/Swift interop boundary. Prevents non-deterministic data races, memory corruption, and Swift 6 runtime actor isolation violations by enforcing Main.immediate dispatcher bridges and explicit unsubscription lifecycles.

Prohibited Anti-Pattern: Direct Unconfined StateFlow Collection Across Kotlin/Native and Swift Actor Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin/Native StateFlow to Swift Actor Dispatcher & Immutability Fence Architecture - Enforces strict dispatcher confinement and deep value immutability when exporting Kotlin Coroutines StateFlow primitives across the Darwin Objective-C/Swift interop boundary. Prevents non-deterministic data races, memory corruption, and Swift 6 runtime actor isolation violations by enforcing Main.immediate dispatcher bridges and explicit unsubscription lifecycles.
globs: **/iosMain/**/*.kt, **/commonMain/**/viewmodel/*.kt, iosApp/**/*.swift, **/interop/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-native-stateflow-thread-confinement-guardrail"
---

# Kotlin/Native StateFlow to Swift Actor Dispatcher & Immutability Fence Architecture

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Direct Unconfined StateFlow Collection Across Kotlin/Native and Swift Actor Boundaries

## System Constraints
You are a Principal Mobile Architect enforcing absolute thread confinement, memory safety, and actor isolation for Kotlin Multiplatform (KMP) targeting Darwin/iOS. Mandate that every reactive StateFlow exposed across interop boundaries is wrapped in a thread-confined adapter bound to Dispatchers.Main.immediate, guarantees immutable value semantics, and integrates cleanly into Swift Concurrency without breaking @MainActor isolation.

## Strict Guidelines
- Engineers MUST NEVER expose raw `StateFlow<T>` or `SharedFlow<T>` directly to Swift/Objective-C interop without an export adapter (e.g., SKIE or custom `CancellableFlow` wrapper).
- All emitted state models crossing the interop fence MUST be deeply immutable Kotlin `data class` types with read-only (`val`) primitives and immutable collections (`kotlinx.collections.immutable` or `List` backed by defensive copies).
- Adapters bridging Flow emissions to iOS runtimes MUST explicitly bind collectors to `Dispatchers.Main.immediate` to ensure sync execution on Darwin's main thread and avoid off-main thread race windows.
- Swift clients MUST consume bridged StateFlow streams exclusively within isolated actors or `@MainActor`-annotated contexts via `AsyncSequence` or explicit cancellation task handles.
- Interop cancellation tokens MUST be deterministically bound to the consuming UI lifecycle (e.g., Swift SwiftUI `.task` modifier or explicit `onDisappear` cancellation) to prevent coroutine leaks across GC/ARC boundaries.
- Kotlin ViewModels MUST NOT expose mutable `MutableStateFlow` instances to the Darwin target under any circumstances; expose only read-only wrapped flow projections.

## Bad vs Good Implementations
### Kotlin/Native Flow Adapter with Thread Confinement

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exposing a raw or mutable flow permits arbitrary thread mutation from Swift, lacks Darwin Dispatchers.Main.immediate confinement, and leaks the coroutine without an explicit, ARC-safe cancellation token.
```kotlin
// BAD: Exposing raw MutableStateFlow or unconfined StateFlow directly to Swift
class UserViewModel : ViewModel() {
    val state: MutableStateFlow<UserState> = MutableStateFlow(UserState())
    
    // Directly called from Swift via unconfined coroutine scope
    fun observeState(onChange: (UserState) -> Unit) {
        viewModelScope.launch {
            state.collect { onChange(it) }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Guarantees read-only state projection, enforces Main.immediate dispatching for zero-latency UI updates on iOS, and returns an explicit disposable token to prevent memory leaks.
```kotlin
// GOOD: Immutable state projection confined to Dispatchers.Main.immediate with explicit disposable token
class UserViewModel : ViewModel() {
    private val _state = MutableStateFlow(UserState())
    val state: StateFlow<UserState> = _state.asStateFlow()

    fun bindState(onEmit: (UserState) -> Unit): InteropDisposable {
        val job = viewModelScope.launch(Dispatchers.Main.immediate) {
            state.collect { onEmit(it) }
        }
        return InteropDisposable { job.cancel() }
    }
}

fun interface InteropDisposable {
    fun dispose()
}
```

### Swift Concurrency MainActor Bridge with AsyncSequence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mutating `@Published` or `@Observable` properties from an unconfined Kotlin/Native callback violates Swift 6 actor isolation, leading to UI thread warnings, torn reads, or crash exceptions.
```swift
// BAD: Escaping isolation and unconfined callback consumption in Swift
class UserViewModelWrapper: ObservableObject {
    @Published var state = UserState()
    private let kmpVm = UserViewModel()

    func startListening() {
        // Escapes thread isolation; callback executes on arbitrary K/N background thread
        kmpVm.observeState { [weak self] newState in
            self?.state = newState // Runtime crash or Purple Warning: mutated off main thread!
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the KMP flow into a Swift AsyncStream fully bound to @MainActor, handling cancellation automatically via Task lifecycle and guaranteeing isolated state mutations.
```swift
// GOOD: Enforcing @MainActor isolation and deterministic Swift Concurrency lifecycle
@MainActor
final class UserViewModelWrapper: ObservableObject {
    @Published private(set) var state: UserState
    private let kmpVm: UserViewModel
    private var observationTask: Task<Void, Never>?

    init(kmpVm: UserViewModel) {
        self.kmpVm = kmpVm
        self.state = kmpVm.state.value
    }

    func activate() {
        observationTask?.cancel()
        observationTask = Task { @MainActor [weak self] in
            guard let self else { return }
            let stream = AsyncStream(UserState.self) { continuation in
                let disposable = self.kmpVm.bindState { state in
                    continuation.yield(state)
                }
                continuation.onTermination = { _ in disposable.dispose() }
            }
            for await updatedState in stream {
                self.state = updatedState
            }
        }
    }

    func deactivate() {
        observationTask?.cancel()
        observationTask = nil
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin/Native StateFlow to Swift Actor Dispatcher & Immutability Fence Architecture

Kotlin/Native StateFlow to Swift Actor Dispatcher & Immutability Fence Architecture defines an industrial-grade behavioral standard for mobile engineering. Enforces strict dispatcher confinement and deep value immutability when exporting Kotlin Coroutines StateFlow primitives across the Darwin Objective-C/Swift interop boundary. Prevents non-deterministic data races, memory corruption, and Swift 6 runtime actor isolation violations by enforcing Main.immediate dispatcher bridges and explicit unsubscription lifecycles. 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: Direct Unconfined StateFlow Collection Across Kotlin/Native and Swift Actor Boundaries 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 DriftDirect Unconfined StateFlow Collection Across Kotlin/Native and Swift Actor BoundariesCritical
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 NEVER expose raw `StateFlow<T>` or `SharedFlow<T>` directly to Swift/Objective-C interop without an export adapter (e.g., SKIE or custom `CancellableFlow` wrapper).

Engineers MUST NEVER expose raw `StateFlow<T>` or `SharedFlow<T>` directly to Swift/Objective-C interop without an export adapter (e.g., SKIE or custom `CancellableFlow` wrapper).

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

All emitted state models crossing the interop fence MUST be deeply immutable Kotlin `data class` types with read-only (`val`) primitives and immutable collections (`kotlinx.collections.immutable` or `List` backed by defensive copies).

All emitted state models crossing the interop fence MUST be deeply immutable Kotlin `data class` types with read-only (`val`) primitives and immutable collections (`kotlinx.collections.immutable` or `List` backed by defensive copies).

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

Adapters bridging Flow emissions to iOS runtimes MUST explicitly bind collectors to `Dispatchers.Main.immediate` to ensure sync execution on Darwin's main thread and avoid off-main thread race windows.

Adapters bridging Flow emissions to iOS runtimes MUST explicitly bind collectors to `Dispatchers.Main.immediate` to ensure sync execution on Darwin's main thread and avoid off-main thread race windows.

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

Swift clients MUST consume bridged StateFlow streams exclusively within isolated actors or `@MainActor`-annotated contexts via `AsyncSequence` or explicit cancellation task handles.

Swift clients MUST consume bridged StateFlow streams exclusively within isolated actors or `@MainActor`-annotated contexts via `AsyncSequence` or explicit cancellation task handles.

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

Interop cancellation tokens MUST be deterministically bound to the consuming UI lifecycle (e.g., Swift SwiftUI `.task` modifier or explicit `onDisappear` cancellation) to prevent coroutine leaks across GC/ARC boundaries.

Interop cancellation tokens MUST be deterministically bound to the consuming UI lifecycle (e.g., Swift SwiftUI `.task` modifier or explicit `onDisappear` cancellation) to prevent coroutine leaks across GC/ARC boundaries.

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

Kotlin ViewModels MUST NOT expose mutable `MutableStateFlow` instances to the Darwin target under any circumstances

Kotlin ViewModels MUST NOT expose mutable `MutableStateFlow` instances to the Darwin target under any circumstances; expose only read-only wrapped flow projections.

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/Native StateFlow to Swift Actor Dispatcher & Immutability Fence Architecture critical for AI coding assistants?

Enforces strict dispatcher confinement and deep value immutability when exporting Kotlin Coroutines StateFlow primitives across the Darwin Objective-C/Swift interop boundary. Prevents non-deterministic data races, memory corruption, and Swift 6 runtime actor isolation violations by enforcing Main.immediate dispatcher bridges and explicit unsubscription lifecycles. 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 (Direct Unconfined StateFlow Collection Across Kotlin/Native and Swift Actor Boundaries) 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/Native