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

Kotlin Multiplatform StateFlow Bridge Deallocation Guardrail

Enforces strict lifecycle-bound subscription cancellation and bidirectional weak-referencing when bridging Kotlin StateFlow and SharedFlow streams across native boundaries to Swift/Objective-C. Prevents zombie coroutine collection jobs and circular ARC-JVM reference retentions that trigger silent permanent memory leaks in native view layers.

Prohibited Anti-Pattern: Unmanaged Cross-Boundary Flow Observation Retaining Native UI via Coroutine Collector Closures

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform StateFlow Bridge Deallocation Guardrail - Enforces strict lifecycle-bound subscription cancellation and bidirectional weak-referencing when bridging Kotlin StateFlow and SharedFlow streams across native boundaries to Swift/Objective-C. Prevents zombie coroutine collection jobs and circular ARC-JVM reference retentions that trigger silent permanent memory leaks in native view layers.
globs: iosApp/**/*.swift, shared/src/commonMain/**/*.kt, shared/src/iosMain/**/*.kt, **/presentation/**/*.kt, **/ui/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-stateflow-bridge-deallocation-guardrail"
---

# Kotlin Multiplatform StateFlow Bridge Deallocation Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unmanaged Cross-Boundary Flow Observation Retaining Native UI via Coroutine Collector Closures

## System Constraints
You are a Principal Software Architect enforcing zero-leak memory invariants across Kotlin Multiplatform and native Swift/Obj-C bridge boundaries. You must prohibit unmanaged cross-runtime event subscriptions, mandate deterministic cancellation of CoroutineScope jobs upon native view deallocation, and enforce non-capturing weak references across ARC boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS bind Kotlin Flow subscriptions in Swift to a cancellable lifecycle handle (e.g., Swift Task cancelled in onDisappear/deinit, or Combine AnyCancellable stored in a CancellableBag).
- Engineers MUST NOT bridge StateFlow to Swift via static or unbounded CoroutineScopes (such as GlobalScope or non-lifecycle-aware ViewModel scopes) without explicit Swift-driven deallocation tokens.
- Code MUST explicitly cancel the underlying Kotlin Job when an iOS UIViewController, SwiftUI View, or native presenter unmounts or deallocates.
- Services MUST utilize SKIE or KMP-NativeCoroutines auto-cancellation semantics where available, rather than naive escaping closure bridges that hold strong references to native callbacks.
- Components NEVER capture strong references to native UI elements (such as UIViewController, UIView, or SwiftUI State models) inside Kotlin-to-Native notification closures.

## Bad vs Good Implementations
### Bridging StateFlow to Swift with Deterministic Lifecycle Cleanup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Kotlin coroutine collector retains the Swift closure, which strongly captures self. Because the return value (the Disposable/Job cancellation handle) is discarded, the coroutine runs indefinitely on the Kotlin side, preventing the UIViewController from ever deallocating.
```swift
// BAD: Naive closure subscription holds strong reference to self and leaks Kotlin Job
class UserProfileViewController: UIViewController {
    private let viewModel = ProfileViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // watch/collect establishes a Kotlin Job that strongly captures this closure
        viewModel.uiState.watch { state in
            self.render(state: state) // Circular retain: Job -> Closure -> self -> viewModel -> Job
        }
    }
    
    private func render(state: ProfileUiState) {
        // Update UI
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Swift Task owns the Kotlin AsyncSequence consumption, cleanly uses [weak self] to prevent retain cycles, and cancels the task upon dismissal and deinit, terminating the underlying Kotlin coroutine collector immediately.
```swift
// GOOD: Weak capture, lifecycle-bound Task cancellation, and explicit Job termination
class UserProfileViewController: UIViewController {
    private let viewModel = ProfileViewModel()
    private var stateObservationTask: Task<Void, Never>?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        stateObservationTask = Task { [weak self] in
            for await state in self?.viewModel.uiState ?? [] {
                guard !Task.isCancelled, let self = self else { break }
                self.render(state: state)
            }
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if isMovingFromParent || isBeingDismissed {
            stateObservationTask?.cancel()
            stateObservationTask = nil
        }
    }
    
    deinit {
        stateObservationTask?.cancel()
    }
    
    private func render(state: ProfileUiState) {
        // Update UI safely
    }
}
```

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 StateFlow Bridge Deallocation Guardrail

Kotlin Multiplatform StateFlow Bridge Deallocation Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict lifecycle-bound subscription cancellation and bidirectional weak-referencing when bridging Kotlin StateFlow and SharedFlow streams across native boundaries to Swift/Objective-C. Prevents zombie coroutine collection jobs and circular ARC-JVM reference retentions that trigger silent permanent memory leaks in native view layers. 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: Unmanaged Cross-Boundary Flow Observation Retaining Native UI via Coroutine Collector Closures 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 DriftUnmanaged Cross-Boundary Flow Observation Retaining Native UI via Coroutine Collector ClosuresCritical
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 Kotlin Flow subscriptions in Swift to a cancellable lifecycle handle (e.g., Swift Task cancelled in onDisappear/deinit, or Combine AnyCancellable stored in a CancellableBag).

Engineers MUST ALWAYS bind Kotlin Flow subscriptions in Swift to a cancellable lifecycle handle (e.g., Swift Task cancelled in onDisappear/deinit, or Combine AnyCancellable stored in a CancellableBag).

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 bridge StateFlow to Swift via static or unbounded CoroutineScopes (such as GlobalScope or non-lifecycle-aware ViewModel scopes) without explicit Swift-driven deallocation tokens.

Engineers MUST NOT bridge StateFlow to Swift via static or unbounded CoroutineScopes (such as GlobalScope or non-lifecycle-aware ViewModel scopes) without explicit Swift-driven deallocation tokens.

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 explicitly cancel the underlying Kotlin Job when an iOS UIViewController, SwiftUI View, or native presenter unmounts or deallocates.

Code MUST explicitly cancel the underlying Kotlin Job when an iOS UIViewController, SwiftUI View, or native presenter unmounts or deallocates.

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 utilize SKIE or KMP-NativeCoroutines auto-cancellation semantics where available, rather than naive escaping closure bridges that hold strong references to native callbacks.

Services MUST utilize SKIE or KMP-NativeCoroutines auto-cancellation semantics where available, rather than naive escaping closure bridges that hold strong references to native callbacks.

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 capture strong references to native UI elements (such as UIViewController, UIView, or SwiftUI State models) inside Kotlin-to-Native notification closures.

Components NEVER capture strong references to native UI elements (such as UIViewController, UIView, or SwiftUI State models) inside Kotlin-to-Native notification closures.

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 StateFlow Bridge Deallocation Guardrail critical for AI coding assistants?

Enforces strict lifecycle-bound subscription cancellation and bidirectional weak-referencing when bridging Kotlin StateFlow and SharedFlow streams across native boundaries to Swift/Objective-C. Prevents zombie coroutine collection jobs and circular ARC-JVM reference retentions that trigger silent permanent memory leaks in native view layers. 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 (Unmanaged Cross-Boundary Flow Observation Retaining Native UI via Coroutine Collector Closures) 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