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

KMP Shared Coroutine and Swift Async Cancellation Hierarchy Guardrail

Enforces deterministic coroutine cancellation and memory reclamation when bridging Kotlin StateFlow/SharedFlow to Swift concurrency on iOS. Prevents zombie coroutine jobs, retain cycles, and background thread leakage caused by unstructured Swift Task allocation and uncancelled Kotlin CoroutineScopes during native view controller deallocation.

Prohibited Anti-Pattern: Unstructured Swift Task bridging to KMP flows without propagating lifecycle cancellation signals to Kotlin CoroutineScopes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Shared Coroutine and Swift Async Cancellation Hierarchy Guardrail - Enforces deterministic coroutine cancellation and memory reclamation when bridging Kotlin StateFlow/SharedFlow to Swift concurrency on iOS. Prevents zombie coroutine jobs, retain cycles, and background thread leakage caused by unstructured Swift Task allocation and uncancelled Kotlin CoroutineScopes during native view controller deallocation.
globs: iosApp/**/*.swift, shared/src/commonMain/**/*.kt, shared/src/iosMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-coroutine-cancellation-ios-lifecycle-guardrail"
---

# KMP Shared Coroutine and Swift Async Cancellation Hierarchy Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unstructured Swift Task bridging to KMP flows without propagating lifecycle cancellation signals to Kotlin CoroutineScopes

## System Constraints
You are a Principal Mobile Architect enforcing Kotlin Multiplatform (KMP) coroutine lifecycle safety across the Kotlin-to-Swift boundary. You must prevent memory leaks, zombie background jobs, and retain cycles by mandating structured cancellation propagation between Swift async/await runtimes and Kotlin CoroutineScopes.

## Strict Guidelines
- Engineers MUST ALWAYS tie Kotlin Flow consumption in Swift to a structured, cancellable lifecycle scope such as SwiftUI `.task { ... }` or an explicit `Task` handle cancelled in UIViewController `deinit` or `viewDidDisappear`.
- Engineers MUST NOT spawn detached or unstructured Swift `Task { ... }` blocks that capture `self` strongly when observing Kotlin Coroutine flows.
- Shared KMP ViewModels MUST expose an explicit teardown/cleanup method (such as `clear()` or `onCleared()`) that cancels their internal `CoroutineScope(SupervisorJob() + Dispatchers.Main)` when native iOS screens are dismissed.
- Bridged async sequences (via SKIE, KMP-NativeCoroutines, or custom wrappers) MUST propagate Swift `Task.isCancelled` signals to the backing Kotlin `Job` via `withTaskCancellationHandler` or equivalent cancellation hooks.
- Components NEVER hold strong reference cycles between iOS native view delegates and long-lived Kotlin Flow collectors.

## Bad vs Good Implementations
### SwiftUI Consumption of KMP StateFlow with Structured Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Launching an unstructured Task inside .onAppear without tracking its handle or cancelling it on unmount causes the Kotlin Flow collector to run indefinitely in the background, retaining the KMP ViewModel and leaking network/memory resources.
```swift
import SwiftUI
import SharedKit

struct UserProfileView: View {
    @StateObject private var viewModel = UserProfileViewModel()
    @State private var state: UserState = .initial

    var body: some View {
        Text(state.name)
            .onAppear {
                // VIOLATION: Unstructured Task detached from SwiftUI lifecycle;
                // escapes onDisappear and keeps collecting indefinitely.
                Task {
                    for await user in self.viewModel.userStateFlow {
                        self.state = user
                    }
                }
            }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes SwiftUI's native `.task` modifier which automatically cancels the Swift Task when the view disappears or unmounts, while also explicitly invoking `clear()` on the KMP ViewModel wrapper to cancel the root Kotlin SupervisorJob.
```swift
import SwiftUI
import SharedKit

struct UserProfileView: View {
    @StateObject private var viewModel = UserProfileViewModelWrapper()
    @State private var state: UserState = .initial

    var body: some View {
        Text(state.name)
            .task {
                // COMPLIANT: SwiftUI .task lifecycle cancels automatically on view dismissal
                do {
                    for await user in viewModel.userStateFlow {
                        self.state = user
                    }
                } catch is CancellationError {
                    // Handled structured cancellation
                } catch {
                    // Handle domain error
                }
            }
            .onDisappear {
                // COMPLIANT: Explicitly cancel underlying Kotlin CoroutineScope
                viewModel.clear()
            }
    }
}
```

### Kotlin Multiplatform ViewModel Lifecycle Teardown Contract

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Without a lifecycle disposal hook (`clear` or `close`), the Swift consumer cannot cancel the `SupervisorJob`. The Kotlin coroutine stays active in the Kotlin/Native heap even if the iOS UIViewController is popped from the UINavigationController.
```kotlin
// VIOLATION: Shared ViewModel does not provide native platform lifecycle cancellation hooks.
package com.example.shared.presentation

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

class UserProfileViewModel {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
    
    val userState: StateFlow<UserState> = repository.observeUser()
        .stateIn(scope, SharingStarted.Eagerly, UserState.Initial)
}
```

#### Production Standard (Correct)
> **Standard**: Inherits from BaseViewModel exposing `clear()` which cancels `viewModelScope`. Uses `SharingStarted.WhileSubscribed(5000)` so upstream Kotlin flows cancel emission when native Swift subscribers drop.
```kotlin
// COMPLIANT: ViewModel implements explicit Closeable / clear contract propagating cancellation down the Job hierarchy.
package com.example.shared.presentation

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

open class BaseViewModel {
    protected val viewModelScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)

    open fun clear() {
        viewModelScope.cancel()
    }
}

class UserProfileViewModel(private val repository: UserRepository) : BaseViewModel() {
    val userState: StateFlow<UserState> = repository.observeUser()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), UserState.Initial)
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Shared Coroutine and Swift Async Cancellation Hierarchy Guardrail

KMP Shared Coroutine and Swift Async Cancellation Hierarchy Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic coroutine cancellation and memory reclamation when bridging Kotlin StateFlow/SharedFlow to Swift concurrency on iOS. Prevents zombie coroutine jobs, retain cycles, and background thread leakage caused by unstructured Swift Task allocation and uncancelled Kotlin CoroutineScopes during native view controller deallocation. 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: Unstructured Swift Task bridging to KMP flows without propagating lifecycle cancellation signals to Kotlin CoroutineScopes 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 DriftUnstructured Swift Task bridging to KMP flows without propagating lifecycle cancellation signals to Kotlin CoroutineScopesCritical
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 tie Kotlin Flow consumption in Swift to a structured, cancellable lifecycle scope such as SwiftUI `.task { ... }` or an explicit `Task` handle cancelled in UIViewController `deinit` or `viewDidDisappear`.

Engineers MUST ALWAYS tie Kotlin Flow consumption in Swift to a structured, cancellable lifecycle scope such as SwiftUI `.task { ... }` or an explicit `Task` handle cancelled in UIViewController `deinit` or `viewDidDisappear`.

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 spawn detached or unstructured Swift `Task { ... }` blocks that capture `self` strongly when observing Kotlin Coroutine flows.

Engineers MUST NOT spawn detached or unstructured Swift `Task { ... }` blocks that capture `self` strongly when observing Kotlin Coroutine flows.

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

Shared KMP ViewModels MUST expose an explicit teardown/cleanup method (such as `clear()` or `onCleared()`) that cancels their internal `CoroutineScope(SupervisorJob() + Dispatchers.Main)` when native iOS screens are dismissed.

Shared KMP ViewModels MUST expose an explicit teardown/cleanup method (such as `clear()` or `onCleared()`) that cancels their internal `CoroutineScope(SupervisorJob() + Dispatchers.Main)` when native iOS screens are 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.
4

Bridged async sequences (via SKIE, KMP-NativeCoroutines, or custom wrappers) MUST propagate Swift `Task.isCancelled` signals to the backing Kotlin `Job` via `withTaskCancellationHandler` or equivalent cancellation hooks.

Bridged async sequences (via SKIE, KMP-NativeCoroutines, or custom wrappers) MUST propagate Swift `Task.isCancelled` signals to the backing Kotlin `Job` via `withTaskCancellationHandler` or equivalent cancellation hooks.

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 hold strong reference cycles between iOS native view delegates and long-lived Kotlin Flow collectors.

Components NEVER hold strong reference cycles between iOS native view delegates and long-lived Kotlin Flow collectors.

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 Shared Coroutine and Swift Async Cancellation Hierarchy Guardrail critical for AI coding assistants?

Enforces deterministic coroutine cancellation and memory reclamation when bridging Kotlin StateFlow/SharedFlow to Swift concurrency on iOS. Prevents zombie coroutine jobs, retain cycles, and background thread leakage caused by unstructured Swift Task allocation and uncancelled Kotlin CoroutineScopes during native view controller deallocation. 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 (Unstructured Swift Task bridging to KMP flows without propagating lifecycle cancellation signals to Kotlin CoroutineScopes) 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