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

KMP-Swift Coroutine Scoping and ARC Lifecycle Invariant

Enforces strict ARC-to-Garbage-Collector lifecycle ownership rules at the Kotlin Multiplatform and Swift boundary. Prevents native iOS retain cycles, zombie tasks, and memory leaks caused by strong references captured inside suspended coroutine continuations and unmanaged Flow collector closures.

Prohibited Anti-Pattern: Bridging Unbounded Kotlin Coroutines Directly to Swift Native Closures Retaining Strong Self References

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP-Swift Coroutine Scoping and ARC Lifecycle Invariant - Enforces strict ARC-to-Garbage-Collector lifecycle ownership rules at the Kotlin Multiplatform and Swift boundary. Prevents native iOS retain cycles, zombie tasks, and memory leaks caused by strong references captured inside suspended coroutine continuations and unmanaged Flow collector closures.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/viewmodel/*.kt, shared/src/commonMain/**/presentation/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-coroutine-lifecycle-scoping"
---

# KMP-Swift Coroutine Scoping and ARC Lifecycle Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bridging Unbounded Kotlin Coroutines Directly to Swift Native Closures Retaining Strong Self References

## System Constraints
You are a Principal Mobile Architect enforcing Kotlin Multiplatform Coroutine Interop Scoping. Mandate invariants that bridge Apple Automatic Reference Counting (ARC) and Kotlin Garbage Collection deterministically without retain cycles.

## Strict Guidelines
- Engineers MUST ALWAYS bind Swift-side coroutine collection and suspend calls to an explicitly cancellable lifecycle (e.g., UIViewController deinit or SwiftUI Task cancellation).
- Engineers MUST NEVER capture strong references to Swift view models, coordinators, or view controllers inside Kotlin Flow collection callbacks or async completion handlers.
- Kotlin-exposed APIs MUST expose explicit cancellation handles or conform to SKIE/KMP-NativeCoroutines lifecycle tokens rather than relying on Kotlin GC to tear down Swift root references.
- Swift closures bridging Kotlin coroutine continuations MUST explicitly declare `[weak self]` in completion handlers and iteration scopes.
- Shared KMP ViewModels MUST expose a distinct, idempotent `onCleared()` / `close()` lifecycle method that cancels child `CoroutineScope` instances when the native hosting view is dismissed.

## Bad vs Good Implementations
### Swift Flow Observation Retain Cycle Prevention

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin's GC-managed Flow observer holds an opaque reference to the native Swift completion block. Because `self` is captured strongly without cancellation handles bound to the UIViewController's deinit, the view controller is pinned in memory indefinitely.
```swift
import shared

final class ProfileViewController: UIViewController {
    private let viewModel = ProfileViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // CRITICAL BUG: Strong reference to self inside unmanaged Swift completion wrapper.
        // Kotlin GC holds the continuation, and the continuation retains `self`, causing a leak.
        viewModel.uiStateFlow.watch { state in
            self.render(state: state)
        }
    }
    
    private func render(state: ProfileState) {
        // UI mutation
    }
}
```

#### Production Standard (Correct)
> **Standard**: The native stream collection uses Swift concurrency with `[weak self]`, breaks the ARC cycle, respects cooperative Task cancellation, and signals `viewModel.onCleared()` to cancel the backing Kotlin CoroutineScope upon deallocation.
```swift
import shared

final class ProfileViewController: UIViewController {
    private let viewModel = ProfileViewModel()
    private var cancellableToken: Task<Void, Never>?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Invariant: Bind collection to Swift Task lifecycle and explicitly use [weak self]
        cancellableToken = Task { [weak self] in
            for await state in self?.viewModel.uiStateStream ?? [] {
                guard !Task.isCancelled, let self = self else { break }
                self.render(state: state)
            }
        }
    }
    
    deinit {
        cancellableToken?.cancel()
        viewModel.onCleared()
    }
    
    private func render(state: ProfileState) {
        // UI mutation
    }
}
```

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-Swift Coroutine Scoping and ARC Lifecycle Invariant

KMP-Swift Coroutine Scoping and ARC Lifecycle Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict ARC-to-Garbage-Collector lifecycle ownership rules at the Kotlin Multiplatform and Swift boundary. Prevents native iOS retain cycles, zombie tasks, and memory leaks caused by strong references captured inside suspended coroutine continuations and unmanaged Flow collector closures. 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: Bridging Unbounded Kotlin Coroutines Directly to Swift Native Closures Retaining Strong Self References 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 DriftBridging Unbounded Kotlin Coroutines Directly to Swift Native Closures Retaining Strong Self ReferencesCritical
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 bind Swift-side coroutine collection and suspend calls to an explicitly cancellable lifecycle (e.g., UIViewController deinit or SwiftUI Task cancellation).

Engineers MUST ALWAYS bind Swift-side coroutine collection and suspend calls to an explicitly cancellable lifecycle (e.g., UIViewController deinit or SwiftUI Task cancellation).

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 NEVER capture strong references to Swift view models, coordinators, or view controllers inside Kotlin Flow collection callbacks or async completion handlers.

Engineers MUST NEVER capture strong references to Swift view models, coordinators, or view controllers inside Kotlin Flow collection callbacks or async completion handlers.

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

Kotlin-exposed APIs MUST expose explicit cancellation handles or conform to SKIE/KMP-NativeCoroutines lifecycle tokens rather than relying on Kotlin GC to tear down Swift root references.

Kotlin-exposed APIs MUST expose explicit cancellation handles or conform to SKIE/KMP-NativeCoroutines lifecycle tokens rather than relying on Kotlin GC to tear down Swift root references.

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 closures bridging Kotlin coroutine continuations MUST explicitly declare `[weak self]` in completion handlers and iteration scopes.

Swift closures bridging Kotlin coroutine continuations MUST explicitly declare `[weak self]` in completion handlers and iteration scopes.

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

Shared KMP ViewModels MUST expose a distinct, idempotent `onCleared()` / `close()` lifecycle method that cancels child `CoroutineScope` instances when the native hosting view is dismissed.

Shared KMP ViewModels MUST expose a distinct, idempotent `onCleared()` / `close()` lifecycle method that cancels child `CoroutineScope` instances when the native hosting view is dismissed.

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-Swift Coroutine Scoping and ARC Lifecycle Invariant critical for AI coding assistants?

Enforces strict ARC-to-Garbage-Collector lifecycle ownership rules at the Kotlin Multiplatform and Swift boundary. Prevents native iOS retain cycles, zombie tasks, and memory leaks caused by strong references captured inside suspended coroutine continuations and unmanaged Flow collector closures. 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 (Bridging Unbounded Kotlin Coroutines Directly to Swift Native Closures Retaining Strong Self References) 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-Swift