This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-compose-darwin-runloop-render-isolation

Compose Multiplatform iOS Darwin RunLoop Rendering Isolation

Mandate strict decoupling of high-frequency reactive event streams from Compose Multiplatform scene invalidation on iOS. Unmitigated state mutations executed on Dispatchers.Main starve the Darwin RunLoop and CADisplayLink callbacks, causing severe frame drops and touch latency.

Prohibited Anti-Pattern: Pumping unthrottled background streams directly into Compose State on Dispatchers.Main on iOS

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform iOS Darwin RunLoop Rendering Isolation - Mandate strict decoupling of high-frequency reactive event streams from Compose Multiplatform scene invalidation on iOS. Unmitigated state mutations executed on Dispatchers.Main starve the Darwin RunLoop and CADisplayLink callbacks, causing severe frame drops and touch latency.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, shared/**/*.kt, composeApp/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-compose-darwin-runloop-render-isolation"
---

# Compose Multiplatform iOS Darwin RunLoop Rendering Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Pumping unthrottled background streams directly into Compose State on Dispatchers.Main on iOS

## System Constraints
You are a Principal Mobile Architect enforcing rendering performance in Kotlin Multiplatform (KMP) using Compose Multiplatform targeting iOS. Your objective is to ensure Compose UI scene invalidation does not saturate the Darwin RunLoop (CFRunLoop) or block Skiko/Metal frame submission. Enforce state conflation, background transformation dispatchers, and frame-budget-aligned UI updates.

## Strict Guidelines
- Engineers MUST ALWAYS ingest, map, and buffer high-frequency data pipelines (e.g., WebSockets, sensors, audio meters, GPS) on Dispatchers.Default, never directly onto Dispatchers.Main.
- Engineers MUST NEVER update Compose MutableState directly inside high-frequency upstream callbacks without explicit downsampling, throttling, or conflation.
- State pipelines exposed to Compose on iOS MUST use .conflate() or frame-rate-aligned flow windowing (e.g., sample/throttleLatest to target refresh rates like 60Hz or 120Hz) to prevent Skiko invalidation floods.
- Code SHOULD leverage derivedStateOf with a custom structural equality policy when binding complex state to composables to prevent redundant recomposition cascades.
- Services MUST route platform rendering synchronization through CADisplayLink-aligned time steps rather than arbitrary timer loops when driving active animations from shared Kotlin code.
- Components NEVER trigger synchronous layout calculations or blocking file/network I/O inside the composition phase or main-thread LaunchedEffects.

## Bad vs Good Implementations
### Decoupling High-Frequency Ingestion via Conflation and Default Dispatcher

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly collecting high-frequency streams on Dispatchers.Main triggers continuous Skiko scene invalidation and layout passes, denying the Darwin RunLoop time to process UIKit touch events and CADisplayLink frame triggers.
```kotlin
class TickerViewModel(private val sensorSource: HighFrequencySensorSource) : ViewModel() {
    var sensorValue by mutableStateOf(0f)
        private set

    init {
        viewModelScope.launch(Dispatchers.Main) {
            // ANTI-PATTERN: Emitting hundreds of events per second directly
            // onto Dispatchers.Main triggers ComposeScene.invalidate() on every tick,
            // saturating the Darwin RunLoop and dropping iOS input touch events.
            sensorSource.rawUpdates.collect { update ->
                sensorValue = update.normalizedMagnitude
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Computations execute off the UI thread via Dispatchers.Default, while conflate() and sample(16L) ensure Compose state mutations are strictly throttled to the frame deadline, allowing the Darwin RunLoop to service UIKit events normally.
```kotlin
class TickerViewModel(private val sensorSource: HighFrequencySensorSource) : ViewModel() {
    var sensorValue by mutableStateOf(0f)
        private set

    init {
        viewModelScope.launch(Dispatchers.Default) {
            // PRODUCTION FIX: Buffer and process heavy calculations off the main thread,
            // conflate rapid bursts, and throttle updates to protect the Darwin RunLoop.
            sensorSource.rawUpdates
                .map { it.computeNormalizedMagnitude() }
                .conflate()
                .sample(16L) // Bound to ~60Hz frame budget
                .flowOn(Dispatchers.Default)
                .collect { processedValue ->
                    withContext(Dispatchers.Main.immediate) {
                        sensorValue = processedValue
                    }
                }
        }
    }
}
```

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: Compose Multiplatform iOS Darwin RunLoop Rendering Isolation

Compose Multiplatform iOS Darwin RunLoop Rendering Isolation defines an industrial-grade behavioral standard for mobile engineering. Mandate strict decoupling of high-frequency reactive event streams from Compose Multiplatform scene invalidation on iOS. Unmitigated state mutations executed on Dispatchers.Main starve the Darwin RunLoop and CADisplayLink callbacks, causing severe frame drops and touch latency. 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: Pumping unthrottled background streams directly into Compose State on Dispatchers.Main on iOS 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 DriftPumping unthrottled background streams directly into Compose State on Dispatchers.Main on iOSCritical
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 ingest, map, and buffer high-frequency data pipelines (e.g., WebSockets, sensors, audio meters, GPS) on Dispatchers.Default, never directly onto Dispatchers.Main.

Engineers MUST ALWAYS ingest, map, and buffer high-frequency data pipelines (e.g., WebSockets, sensors, audio meters, GPS) on Dispatchers.Default, never directly onto Dispatchers.Main.

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 NEVER update Compose MutableState directly inside high-frequency upstream callbacks without explicit downsampling, throttling, or conflation.

Engineers MUST NEVER update Compose MutableState directly inside high-frequency upstream callbacks without explicit downsampling, throttling, or conflation.

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

State pipelines exposed to Compose on iOS MUST use .conflate() or frame-rate-aligned flow windowing (e.g., sample/throttleLatest to target refresh rates like 60Hz or 120Hz) to prevent Skiko invalidation floods.

State pipelines exposed to Compose on iOS MUST use .conflate() or frame-rate-aligned flow windowing (e.g., sample/throttleLatest to target refresh rates like 60Hz or 120Hz) to prevent Skiko invalidation floods.

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

Code SHOULD leverage derivedStateOf with a custom structural equality policy when binding complex state to composables to prevent redundant recomposition cascades.

Code SHOULD leverage derivedStateOf with a custom structural equality policy when binding complex state to composables to prevent redundant recomposition cascades.

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

Services MUST route platform rendering synchronization through CADisplayLink-aligned time steps rather than arbitrary timer loops when driving active animations from shared Kotlin code.

Services MUST route platform rendering synchronization through CADisplayLink-aligned time steps rather than arbitrary timer loops when driving active animations from shared Kotlin code.

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.
6

Components NEVER trigger synchronous layout calculations or blocking file/network I/O inside the composition phase or main-thread LaunchedEffects.

Components NEVER trigger synchronous layout calculations or blocking file/network I/O inside the composition phase or main-thread LaunchedEffects.

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 Compose Multiplatform iOS Darwin RunLoop Rendering Isolation critical for AI coding assistants?

Mandate strict decoupling of high-frequency reactive event streams from Compose Multiplatform scene invalidation on iOS. Unmitigated state mutations executed on Dispatchers.Main starve the Darwin RunLoop and CADisplayLink callbacks, causing severe frame drops and touch latency. 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 (Pumping unthrottled background streams directly into Compose State on Dispatchers.Main on iOS) 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

Compose