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

KMP Bi-Directional Swift Task to Coroutine Cancellation Bridge

Enforces deterministic, bi-directional cooperative cancellation bridging between Swift async/await Tasks and Kotlin Coroutine Jobs across the Kotlin/Native boundary. Eliminates orphaned background execution threads, UI memory retention cycles, and phantom network operations when Swift views discard active tasks.

Prohibited Anti-Pattern: Orphaned Kotlin Coroutine Execution on Swift Task Cancellation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Bi-Directional Swift Task to Coroutine Cancellation Bridge - Enforces deterministic, bi-directional cooperative cancellation bridging between Swift async/await Tasks and Kotlin Coroutine Jobs across the Kotlin/Native boundary. Eliminates orphaned background execution threads, UI memory retention cycles, and phantom network operations when Swift views discard active tasks.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt, **/*Bridge*.swift, **/*Adapter*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-task-cancellation-bridge-standard"
---

# KMP Bi-Directional Swift Task to Coroutine Cancellation Bridge

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Orphaned Kotlin Coroutine Execution on Swift Task Cancellation

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Swift Concurrency interoperability. You strictly mandate that every Kotlin suspend function or Flow consumed by Swift async/await tasks guarantees deterministic bi-directional cancellation propagation. Never allow unmanaged suspend invocations or detached CoroutineScopes that do not bind Swift Task lifecycle to Kotlin Job lifecycle.

## Strict Guidelines
- Engineers MUST ALWAYS wrap raw Kotlin/Native suspend exports with `withTaskCancellationHandler` in Swift or rely on verified structured concurrency adapters (e.g., SKIE or KMP-NativeCoroutines) that bind Swift cancellation directly to `Job.cancel()`.
- Engineers MUST NOT invoke Kotlin suspend functions directly via raw Swift `async` wrappers without binding the Swift cancellation handler to the returned Kotlin `Cancellable` or `Job` handle.
- Kotlin iOS bridge interfaces MUST return a handle exposing `cancel()` or accept a cooperative cancellation token across the Objective-C bridging barrier.
- Shared Flows exposed to iOS MUST be collected using a lifecycle-aware wrapper that cancels the underlying Kotlin `Job` immediately when the Swift `AsyncSequence` terminates or throws `CancellationError`.
- SwiftUI views MUST NEVER fire-and-forget Kotlin coroutines in `.task` or `.onAppear` without structured cancellation hooks; abandoning a view MUST immediately propagate cancellation down to active CoroutineContext dispatchers.

## Bad vs Good Implementations
### Bridging Swift Task Cancellation to Kotlin Coroutine Job

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default Objective-C Swift interop generates an async wrapper for suspend functions, but Swift Task cancellation does not propagate to the underlying Kotlin Job. The background thread in Kotlin continues executing unobserved, wasting battery, network, and memory.
```swift
import SharedKit

final class ProfileViewModel: ObservableObject {
    private let repository: UserProfileRepository
    
    init(repository: UserProfileRepository) {
        self.repository = repository
    }
    
    func loadProfile(userId: String) async throws -> UserProfile {
        // ANTI-PATTERN: Direct invocation of unbridged suspend function.
        // If the Swift Task is cancelled (e.g. view dismissed), the underlying
        // Kotlin coroutine continues executing on Dispatchers.Default unchecked.
        return try await repository.fetchUserProfile(id: userId)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the bridging continuation in `withTaskCancellationHandler` to immediately trigger the Kotlin `CancellableHandle.cancel()` upon Swift Task cancellation, ensuring instantaneous termination of background work.
```swift
import SharedKit

final class ProfileViewModel: ObservableObject {
    private let repository: UserProfileRepository
    
    init(repository: UserProfileRepository) {
        self.repository = repository
    }
    
    func loadProfile(userId: String) async throws -> UserProfile {
        // PRODUCTION INVARIANT: Cooperative bi-directional cancellation bridge.
        var cancellableHandle: CancellableHandle? = nil
        
        return try await withTaskCancellationHandler {
            try Task.checkCancellation()
            return try await withCheckedThrowingContinuation { continuation in
                cancellableHandle = repository.fetchUserProfileWithCancel(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: {
            // Propagates Swift Task cancellation directly into Kotlin Job.cancel()
            cancellableHandle?.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: KMP Bi-Directional Swift Task to Coroutine Cancellation Bridge

KMP Bi-Directional Swift Task to Coroutine Cancellation Bridge defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic, bi-directional cooperative cancellation bridging between Swift async/await Tasks and Kotlin Coroutine Jobs across the Kotlin/Native boundary. Eliminates orphaned background execution threads, UI memory retention cycles, and phantom network operations when Swift views discard active tasks. 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 Execution on Swift 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 Execution on Swift 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 Kotlin/Native suspend exports with `withTaskCancellationHandler` in Swift or rely on verified structured concurrency adapters (e.g., SKIE or KMP-NativeCoroutines) that bind Swift cancellation directly to `Job.cancel()`.

Engineers MUST ALWAYS wrap raw Kotlin/Native suspend exports with `withTaskCancellationHandler` in Swift or rely on verified structured concurrency adapters (e.g., SKIE or KMP-NativeCoroutines) that bind Swift cancellation directly to `Job.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.
2

Engineers MUST NOT invoke Kotlin suspend functions directly via raw Swift `async` wrappers without binding the Swift cancellation handler to the returned Kotlin `Cancellable` or `Job` handle.

Engineers MUST NOT invoke Kotlin suspend functions directly via raw Swift `async` wrappers without binding the Swift cancellation handler to the returned Kotlin `Cancellable` or `Job` handle.

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 iOS bridge interfaces MUST return a handle exposing `cancel()` or accept a cooperative cancellation token across the Objective-C bridging barrier.

Kotlin iOS bridge interfaces MUST return a handle exposing `cancel()` or accept a cooperative cancellation token across the Objective-C bridging barrier.

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

Shared Flows exposed to iOS MUST be collected using a lifecycle-aware wrapper that cancels the underlying Kotlin `Job` immediately when the Swift `AsyncSequence` terminates or throws `CancellationError`.

Shared Flows exposed to iOS MUST be collected using a lifecycle-aware wrapper that cancels the underlying Kotlin `Job` immediately when the Swift `AsyncSequence` terminates or throws `CancellationError`.

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

SwiftUI views MUST NEVER fire-and-forget Kotlin coroutines in `.task` or `.onAppear` without structured cancellation hooks

SwiftUI views MUST NEVER fire-and-forget Kotlin coroutines in `.task` or `.onAppear` without structured cancellation hooks; abandoning a view MUST immediately propagate cancellation down to active CoroutineContext dispatchers.

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

Enforces deterministic, bi-directional cooperative cancellation bridging between Swift async/await Tasks and Kotlin Coroutine Jobs across the Kotlin/Native boundary. Eliminates orphaned background execution threads, UI memory retention cycles, and phantom network operations when Swift views discard active tasks. 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 Execution on Swift 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

KMP