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

Kotlin Multiplatform Coroutine to Swift Task Bi-Directional Cancellation Propagation

Enforces strict cooperative cancellation bridges between Kotlin Native Coroutines and Swift Concurrency Task hierarchies in Kotlin Multiplatform (KMP) iOS targets. Prevents detached task leaks, runaway thread execution, and silent memory retain cycles across the Obj-C runtime bridge by mandating explicit withTaskCancellationHandler wrapping and Swift Task-to-Job cancellation propagation hooks.

Prohibited Anti-Pattern: Orphaned Kotlin Coroutine Jobs Executing After Swift UI/Task Cancellation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Coroutine to Swift Task Bi-Directional Cancellation Propagation - Enforces strict cooperative cancellation bridges between Kotlin Native Coroutines and Swift Concurrency Task hierarchies in Kotlin Multiplatform (KMP) iOS targets. Prevents detached task leaks, runaway thread execution, and silent memory retain cycles across the Obj-C runtime bridge by mandating explicit withTaskCancellationHandler wrapping and Swift Task-to-Job cancellation propagation hooks.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt, **/*Bridge*.swift, **/*ViewModel*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-coroutine-swift-task-cancellation-propagation"
---

# Kotlin Multiplatform Coroutine to Swift Task Bi-Directional Cancellation Propagation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Orphaned Kotlin Coroutine Jobs Executing After Swift UI/Task Cancellation

## System Constraints
You are a Principal Mobile Architect enforcing rock-solid concurrency invariants between Kotlin Multiplatform (KMP) and Swift Concurrency on iOS. When exposing Kotlin Coroutines (suspend functions, Flow) to Swift or wrapping Swift async/await tasks inside Kotlin Native, you must enforce cooperative bi-directional cancellation. The default Obj-C export transforms suspend functions into completion handlers with an `NSError` callback, dropping Swift Task cancellation semantics entirely. You MUST mandate `withTaskCancellationHandler` or SKIE-generated async wrappers that wire `Task.isCancelled` directly to Kotlin's `Job.cancel()`, ensuring no detached threads consume battery, bandwidth, or CPU in the background.

## Strict Guidelines
- Engineers MUST ALWAYS wrap raw Objective-C/Swift async bridge bridges using `withTaskCancellationHandler` or use vetted toolchains like SKIE that generate native Swift cancellation tokens bound to Kotlin `Job` handles.
- Engineers MUST NOT rely on default Swift-ObjC completion-handler-to-async bridging for Kotlin suspend functions without an explicit cancellation handler invoking the Kotlin Job's `cancel()`.
- Code MUST explicitly propagate Swift structured concurrency cancellation downwards into Kotlin `Job.cancel(CancellationException())` to preempt unmanaged coroutine continuation.
- Services exposing Kotlin `Flow` to Swift MUST return a disposable handle or `Cancellable` wrapper, and the Swift consuming `AsyncSequence` MUST cancel the underlying Kotlin collector when the consuming Swift Task is cancelled or falls out of scope.
- Components NEVER store long-lived strong references to Kotlin `Job` or Swift `Task` instances in bridging closures, preventing ARC-to-Kotlin GC reference cycles across the foreign function interface.

## Bad vs Good Implementations
### Bi-Directional Bridging of Kotlin Suspend Function to Swift Task

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default Swift async/await wrapper for KMP suspend functions passes a completion handler but does not attach a Swift Task cancellation hook to the underlying Kotlin Job. If the user navigates away or the view unmounts, the Kotlin coroutine continues executing network/DB tasks, leaking resources.
```swift
// BAD: Native Swift async conversion drops cancellation propagation to Kotlin Native
func fetchUserData(userId: String) async throws -> UserProfile {
    // Standard Swift bridged suspend function from KMP
    // If this Swift Task is cancelled (e.g., SwiftUI view unmounts),
    // the underlying Kotlin Coroutine remains alive and continues executing on background threads!
    return try await kmpUserRepository.fetchUserProfile(id: userId)
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping the invocation in `withTaskCancellationHandler` ensures that when the parent Swift Task is cancelled, `onCancel` immediately invokes `cancel()` on the Kotlin `Job`, immediately halting Kotlin Native background execution.
```swift
// GOOD: Explicit cooperative cancellation binding Swift Task to Kotlin Job
func fetchUserData(userId: String) async throws -> UserProfile {
    var kotlinJob: KMPCommonJob? = nil
    
    return try await withTaskCancellationHandler {
        try Task.checkCancellation()
        return try await withCheckedThrowingContinuation { continuation in
            kotlinJob = kmpUserRepository.fetchUserProfile(id: userId) { profile, error in
                if let error = error {
                    continuation.resume(throwing: error)
                } else if let profile = profile {
                    continuation.resume(returning: profile)
                } else {
                    continuation.resume(throwing: CancellationError())
                }
            }
        }
    } onCancel: {
        // Cooperative propagation: Cancelling the Swift Task cancels the Kotlin Job
        kotlinJob?.cancel(cause: nil)
    }
}
```

### Kotlin Native Flow to Swift AsyncSequence Cancellation Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The underlying Kotlin Flow collection continues in the background indefinitely even if the Swift consumer breaks out of the loop or the consuming Task is cancelled, because the cancellation closure was never wired to the Kotlin Job cancellation mechanism.
```swift
// BAD: Flow collector runs unbounded; Swift iteration break leaves collector alive in Kotlin
func observeUserUpdates() -> AsyncStream<UserData> {
    AsyncStream { continuation in
        kmpUserRepository.userUpdatesFlow.collect(collector: FlowCollector { data in
            continuation.yield(data)
        }) { error in
            continuation.finish()
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Wiring `continuation.onTermination` directly to the Kotlin `cancellable.cancel()` guarantees that terminating or cancelling the Swift consumer immediately stops the Kotlin Flow emission upstream.
```swift
// GOOD: Swift AsyncStream lifecycle actively controls Kotlin Flow coroutine scope cancellation
func observeUserUpdates() -> AsyncStream<UserData> {
    AsyncStream { continuation in
        let cancellable = kmpUserRepository.userUpdatesFlow.watch { data in
            continuation.yield(data)
        }
        
        continuation.onTermination = { @Sendable termination in
            // Clean up Kotlin coroutine scope when Swift stream finishes or is cancelled
            cancellable.cancel()
        }
    }
}
```

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 Coroutine to Swift Task Bi-Directional Cancellation Propagation

Kotlin Multiplatform Coroutine to Swift Task Bi-Directional Cancellation Propagation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cooperative cancellation bridges between Kotlin Native Coroutines and Swift Concurrency Task hierarchies in Kotlin Multiplatform (KMP) iOS targets. Prevents detached task leaks, runaway thread execution, and silent memory retain cycles across the Obj-C runtime bridge by mandating explicit withTaskCancellationHandler wrapping and Swift Task-to-Job cancellation propagation hooks. 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: Orphaned Kotlin Coroutine Jobs Executing After Swift UI/Task Cancellation 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 DriftOrphaned Kotlin Coroutine Jobs Executing After Swift UI/Task CancellationCritical
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 wrap raw Objective-C/Swift async bridge bridges using `withTaskCancellationHandler` or use vetted toolchains like SKIE that generate native Swift cancellation tokens bound to Kotlin `Job` handles.

Engineers MUST ALWAYS wrap raw Objective-C/Swift async bridge bridges using `withTaskCancellationHandler` or use vetted toolchains like SKIE that generate native Swift cancellation tokens bound to Kotlin `Job` handles.

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 rely on default Swift-ObjC completion-handler-to-async bridging for Kotlin suspend functions without an explicit cancellation handler invoking the Kotlin Job's `cancel()`.

Engineers MUST NOT rely on default Swift-ObjC completion-handler-to-async bridging for Kotlin suspend functions without an explicit cancellation handler invoking the Kotlin Job's `cancel()`.

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 propagate Swift structured concurrency cancellation downwards into Kotlin `Job.cancel(CancellationException())` to preempt unmanaged coroutine continuation.

Code MUST explicitly propagate Swift structured concurrency cancellation downwards into Kotlin `Job.cancel(CancellationException())` to preempt unmanaged coroutine continuation.

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 exposing Kotlin `Flow` to Swift MUST return a disposable handle or `Cancellable` wrapper, and the Swift consuming `AsyncSequence` MUST cancel the underlying Kotlin collector when the consuming Swift Task is cancelled or falls out of scope.

Services exposing Kotlin `Flow` to Swift MUST return a disposable handle or `Cancellable` wrapper, and the Swift consuming `AsyncSequence` MUST cancel the underlying Kotlin collector when the consuming Swift Task is cancelled or falls out of scope.

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 store long-lived strong references to Kotlin `Job` or Swift `Task` instances in bridging closures, preventing ARC-to-Kotlin GC reference cycles across the foreign function interface.

Components NEVER store long-lived strong references to Kotlin `Job` or Swift `Task` instances in bridging closures, preventing ARC-to-Kotlin GC reference cycles across the foreign function interface.

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 Coroutine to Swift Task Bi-Directional Cancellation Propagation critical for AI coding assistants?

Enforces strict cooperative cancellation bridges between Kotlin Native Coroutines and Swift Concurrency Task hierarchies in Kotlin Multiplatform (KMP) iOS targets. Prevents detached task leaks, runaway thread execution, and silent memory retain cycles across the Obj-C runtime bridge by mandating explicit withTaskCancellationHandler wrapping and Swift Task-to-Job cancellation propagation hooks. 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 (Orphaned Kotlin Coroutine Jobs Executing After Swift UI/Task Cancellation) 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