This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-skie-flow-cancellation-swiftui-binding

KMP SKIE Flow-Cancellation-to-SwiftUI-Task Lifecycle Binding

Enforces deterministic coroutine cancellation bridging between Touchlab SKIE-generated Swift AsyncSequences and SwiftUI lifecycle tasks. Prevents unmanaged Kotlin coroutine leaks, orphaned background processing, and iOS Darwin dispatcher thread starvation caused by escaping structured concurrency boundaries.

Prohibited Anti-Pattern: Unstructured Flow Collection via Escaped Tasks or onAppear Lifecycle Callbacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP SKIE Flow-Cancellation-to-SwiftUI-Task Lifecycle Binding - Enforces deterministic coroutine cancellation bridging between Touchlab SKIE-generated Swift AsyncSequences and SwiftUI lifecycle tasks. Prevents unmanaged Kotlin coroutine leaks, orphaned background processing, and iOS Darwin dispatcher thread starvation caused by escaping structured concurrency boundaries.
globs: iosApp/**/*.swift, **/*View.swift, **/*ViewModel.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skie-flow-cancellation-swiftui-binding"
---

# KMP SKIE Flow-Cancellation-to-SwiftUI-Task Lifecycle Binding

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unstructured Flow Collection via Escaped Tasks or onAppear Lifecycle Callbacks

## System Constraints
You are a Principal Mobile Architect enforcing strict lifecycle bindings between Kotlin Multiplatform (KMP) SKIE-generated Swift wrappers and SwiftUI. SKIE transforms Kotlin Coroutine Flows into Swift AsyncSequences. You must enforce that all SKIE AsyncSequence collections participate strictly in Swift Structured Concurrency tied directly to SwiftUI's `.task` modifier or structured cancellable task handles in ViewModels. Never allow unmanaged Tasks, escaping closures in onAppear, or suppressed Swift CancellationErrors, as doing so fails to trigger Kotlin Job.cancel(), resulting in orphan coroutines and native thread starvation.

## Strict Guidelines
- Engineers MUST ALWAYS consume SKIE-generated Flow AsyncSequences using SwiftUI's native `.task` or `.task(id:)` lifecycle modifiers to guarantee automatic Task cancellation on view dismissal.
- Engineers MUST NOT spawn detached or unmanaged `Task { ... }` blocks inside `onAppear` or unconstrained closures to collect SKIE Flows.
- ViewModels bridging SKIE Flows to `@Observable` or `@Published` state MUST retain a dedicated `Task<Void, Never>?` reference and explicitly cancel it in `deinit` or an explicit cleanup hook.
- Swift code consuming SKIE AsyncSequences MUST NOT swallow `CancellationError`; `CancellationError` MUST be allowed to propagate to trigger native Kotlin Job cancellation.
- Components NEVER collect multiple infinite SKIE Flows in sequence inside the same `.task` without parallel structured child tasks (`async let` or `withTaskGroup`), as the first Flow will block subsequent collections permanently.

## Bad vs Good Implementations
### SwiftUI SKIE Flow Lifecycle Collection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Launching an unstructured Task in .onAppear disconnects the asynchronous work from SwiftUI's view lifecycle. View dismissal will not cancel the Task, preventing SKIE from propagating cancellation to the Kotlin Job, which leaks native resources and leads to thread pool starvation on Darwin.
```swift
import SwiftUI
import SharedKit

struct ProfileView: View {
    @StateObject private var viewModel = ProfileViewModel()
    
    var body: some View {
        Text(viewModel.statusText)
            .onAppear {
                // CRITICAL ANTI-PATTERN: Escaping unstructured Task inside onAppear
                // When ProfileView pops from NavigationStack, this Task continues running,
                // leaving the underlying Kotlin Coroutine active and leaking memory/threads.
                Task {
                    do {
                        for await update in viewModel.repository.observeStatus() {
                            viewModel.statusText = update.title
                        }
                    } catch {
                        // SWALLOWING CancellationError suppresses Kotlin Job cancellation
                        print("Error: \(error)")
                    }
                }
            }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Using SwiftUI's .task modifier ensures structured cancellation propagation. When the view disappears, the task is automatically cancelled. SKIE intercepts the Swift CancellationError and cancels the corresponding Kotlin Coroutine Job, preventing leaks.
```swift
import SwiftUI
import SharedKit

struct ProfileView: View {
    @State private var statusText: String = "Initializing..."
    let repository: StatusRepository
    
    var body: some View {
        Text(statusText)
            // PRODUCTION STANDARD: .task automatically binds lifecycle cancellation
            // When ProfileView unmounts, SwiftUI cancels the Task, SKIE catches the
            // Swift CancellationError, and triggers Job.cancel() in Kotlin Coroutines.
            .task {
                do {
                    for await update in repository.observeStatus() {
                        self.statusText = update.title
                    }
                } catch is CancellationError {
                    // Explicit cooperative cancellation pass-through
                    // SKIE properly receives the signal to cancel the underlying Kotlin Job
                } catch {
                    self.statusText = "Error loading status"
                }
            }
    }
}
```

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 SKIE Flow-Cancellation-to-SwiftUI-Task Lifecycle Binding

KMP SKIE Flow-Cancellation-to-SwiftUI-Task Lifecycle Binding defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic coroutine cancellation bridging between Touchlab SKIE-generated Swift AsyncSequences and SwiftUI lifecycle tasks. Prevents unmanaged Kotlin coroutine leaks, orphaned background processing, and iOS Darwin dispatcher thread starvation caused by escaping structured concurrency boundaries. 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 Flow Collection via Escaped Tasks or onAppear Lifecycle Callbacks 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 Flow Collection via Escaped Tasks or onAppear Lifecycle CallbacksCritical
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 consume SKIE-generated Flow AsyncSequences using SwiftUI's native `.task` or `.task(id

Engineers MUST ALWAYS consume SKIE-generated Flow AsyncSequences using SwiftUI's native `.task` or `.task(id:)` lifecycle modifiers to guarantee automatic Task cancellation on view dismissal.

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 unmanaged `Task { ... }` blocks inside `onAppear` or unconstrained closures to collect SKIE Flows.

Engineers MUST NOT spawn detached or unmanaged `Task { ... }` blocks inside `onAppear` or unconstrained closures to collect SKIE 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

ViewModels bridging SKIE Flows to `@Observable` or `@Published` state MUST retain a dedicated `Task<Void, Never>?` reference and explicitly cancel it in `deinit` or an explicit cleanup hook.

ViewModels bridging SKIE Flows to `@Observable` or `@Published` state MUST retain a dedicated `Task<Void, Never>?` reference and explicitly cancel it in `deinit` or an explicit cleanup hook.

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 code consuming SKIE AsyncSequences MUST NOT swallow `CancellationError`

Swift code consuming SKIE AsyncSequences MUST NOT swallow `CancellationError`; `CancellationError` MUST be allowed to propagate to trigger native Kotlin Job 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.
5

Components NEVER collect multiple infinite SKIE Flows in sequence inside the same `.task` without parallel structured child tasks (`async let` or `withTaskGroup`), as the first Flow will block subsequent collections permanently.

Components NEVER collect multiple infinite SKIE Flows in sequence inside the same `.task` without parallel structured child tasks (`async let` or `withTaskGroup`), as the first Flow will block subsequent collections permanently.

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 SKIE Flow-Cancellation-to-SwiftUI-Task Lifecycle Binding critical for AI coding assistants?

Enforces deterministic coroutine cancellation bridging between Touchlab SKIE-generated Swift AsyncSequences and SwiftUI lifecycle tasks. Prevents unmanaged Kotlin coroutine leaks, orphaned background processing, and iOS Darwin dispatcher thread starvation caused by escaping structured concurrency boundaries. 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 Flow Collection via Escaped Tasks or onAppear Lifecycle Callbacks) 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