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

KMP StateFlow to Swift AsyncStream Memory Safety and Lifecycle Protocol

Enforces strict cancellation hooks and memory decoupling when bridging Kotlin Multiplatform StateFlow instances into Swift TaskGroup-managed AsyncStreams. Prevents silent ARC/Kotlin GC retain cycles and thread-confinement panics caused by indefinite Native Job references surviving Swift Task cancellations.

Prohibited Anti-Pattern: Unregistered Kotlin Job Cancellations in Swift TaskGroup Producing ARC Zombie Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP StateFlow to Swift AsyncStream Memory Safety and Lifecycle Protocol - Enforces strict cancellation hooks and memory decoupling when bridging Kotlin Multiplatform StateFlow instances into Swift TaskGroup-managed AsyncStreams. Prevents silent ARC/Kotlin GC retain cycles and thread-confinement panics caused by indefinite Native Job references surviving Swift Task cancellations.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-concurrency-stateflow-boundary"
---

# KMP StateFlow to Swift AsyncStream Memory Safety and Lifecycle Protocol

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unregistered Kotlin Job Cancellations in Swift TaskGroup Producing ARC Zombie Leaks

## System Constraints
You are a Principal Mobile Architect enforcing the Kotlin Multiplatform (KMP) Swift Concurrency Memory Boundary Protocol. You must ensure that every Kotlin StateFlow subscribed within Swift via AsyncStream or TaskGroup explicitly installs an onTermination lifecycle hook that terminates the underlying Kotlin CoroutineScope/Job. Never allow strong captured self references inside Swift async adapters bridged to Kotlin closures.

## Strict Guidelines
- Engineers MUST ALWAYS implement withTaskCancellationHandler or AsyncStream.Continuation.onTermination to invoke Kotlin's Job.cancel() when bridging Coroutine flows to Swift.
- Engineers MUST NOT capture strong references to Swift actors, ViewModels, or native bridge controllers inside KMP observation lambdas.
- Code MUST isolate raw Kotlin flow collector scopes to a dedicated Swift actor or @MainActor boundary depending on consumption semantics.
- Services MUST explicitly discard KMP observation tokens or Cancellable wrappers inside Swift deinit or async defer statements.
- Components NEVER bridge raw Flow/StateFlow without an intermediate Swift AsyncSequence wrapper enforcing Swift Structured Concurrency.

## Bad vs Good Implementations
### Bridging Kotlin StateFlow into Swift AsyncStream with Lifecycle Binding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: FlowCollector closure strongly captures self and retains an unmanaged Kotlin Coroutine Job without registering an AsyncStream.onTermination handler. When the consuming Swift Task is cancelled, the Kotlin Flow remains collected, leaking memory across the Obj-C runtime boundary.
```swift
import Shared

final class ObservableStateHolder {
    private let kotlinViewModel: SharedViewModel
    
    init(kotlinViewModel: SharedViewModel) {
        self.kotlinViewModel = kotlinViewModel
    }
    
    // LEAK: Indefinite collector retain cycle; ignores Swift Task cancellation
    func streamState() -> AsyncStream<String> {
        AsyncStream { continuation in
            self.kotlinViewModel.uiState.collect(collector: FlowCollector { value in
                continuation.yield(value as? String ?? "")
            }) { error in
                continuation.finish()
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Uses weak capture of the underlying Kotlin reference and attaches an explicit continuation.onTermination hook. Calling closeable.close() cancels the underlying Kotlin Job when the Swift AsyncStream scope exits, preventing ARC zombie leaks.
```swift
import Shared

final class ObservableStateHolder {
    private let kotlinViewModel: SharedViewModel
    
    init(kotlinViewModel: SharedViewModel) {
        self.kotlinViewModel = kotlinViewModel
    }
    
    func streamState() -> AsyncStream<String> {
        AsyncStream { [weak kotlinViewModel] continuation in
            guard let kotlinViewModel else { continuation.finish(); return }
            
            let closeable = kotlinViewModel.uiState.watch { state in
                continuation.yield(state as? String ?? "")
            }
            
            // MANDATED: Propagate Swift Task/Stream lifecycle termination to Kotlin GC boundary
            continuation.onTermination = { @Sendable _ in
                closeable.close()
            }
        }
    }
}
```

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: KMP StateFlow to Swift AsyncStream Memory Safety and Lifecycle Protocol

KMP StateFlow to Swift AsyncStream Memory Safety and Lifecycle Protocol defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cancellation hooks and memory decoupling when bridging Kotlin Multiplatform StateFlow instances into Swift TaskGroup-managed AsyncStreams. Prevents silent ARC/Kotlin GC retain cycles and thread-confinement panics caused by indefinite Native Job references surviving Swift Task cancellations. 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: Unregistered Kotlin Job Cancellations in Swift TaskGroup Producing ARC Zombie Leaks 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 DriftUnregistered Kotlin Job Cancellations in Swift TaskGroup Producing ARC Zombie LeaksCritical
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 implement withTaskCancellationHandler or AsyncStream.Continuation.onTermination to invoke Kotlin's Job.cancel() when bridging Coroutine flows to Swift.

Engineers MUST ALWAYS implement withTaskCancellationHandler or AsyncStream.Continuation.onTermination to invoke Kotlin's Job.cancel() when bridging Coroutine flows to Swift.

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 capture strong references to Swift actors, ViewModels, or native bridge controllers inside KMP observation lambdas.

Engineers MUST NOT capture strong references to Swift actors, ViewModels, or native bridge controllers inside KMP observation lambdas.

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 MUST isolate raw Kotlin flow collector scopes to a dedicated Swift actor or @MainActor boundary depending on consumption semantics.

Code MUST isolate raw Kotlin flow collector scopes to a dedicated Swift actor or @MainActor boundary depending on consumption semantics.

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 explicitly discard KMP observation tokens or Cancellable wrappers inside Swift deinit or async defer statements.

Services MUST explicitly discard KMP observation tokens or Cancellable wrappers inside Swift deinit or async defer statements.

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 bridge raw Flow/StateFlow without an intermediate Swift AsyncSequence wrapper enforcing Swift Structured Concurrency.

Components NEVER bridge raw Flow/StateFlow without an intermediate Swift AsyncSequence wrapper enforcing Swift Structured Concurrency.

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 KMP StateFlow to Swift AsyncStream Memory Safety and Lifecycle Protocol critical for AI coding assistants?

Enforces strict cancellation hooks and memory decoupling when bridging Kotlin Multiplatform StateFlow instances into Swift TaskGroup-managed AsyncStreams. Prevents silent ARC/Kotlin GC retain cycles and thread-confinement panics caused by indefinite Native Job references surviving Swift Task cancellations. 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 (Unregistered Kotlin Job Cancellations in Swift TaskGroup Producing ARC Zombie Leaks) 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

KMP