This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-stateflow-recomposition-debounce-barrier

KMP StateFlow Telemetry Debounce & Conflation Barrier for Declarative UI

High-frequency streaming inputs (e.g., BLE packets, GPS fixes, sensor feeds, audio telemetry) emitted directly into shared Kotlin Multiplatform StateFlow pipelines saturate the main UI thread in Jetpack Compose and SwiftUI. Shared ViewModels must enforce a conflation and temporal sampling barrier on Dispatchers.Default before exposing UI state. This guarantees that frame rendering cycles (60Hz/120Hz) are never overwhelmed by non-visual intermediary state mutations.

Prohibited Anti-Pattern: Binding Unbounded High-Frequency Telemetry Flows Directly to UI StateFlows Without Conflation Barriers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP StateFlow Telemetry Debounce & Conflation Barrier for Declarative UI - High-frequency streaming inputs (e.g., BLE packets, GPS fixes, sensor feeds, audio telemetry) emitted directly into shared Kotlin Multiplatform StateFlow pipelines saturate the main UI thread in Jetpack Compose and SwiftUI. Shared ViewModels must enforce a conflation and temporal sampling barrier on Dispatchers.Default before exposing UI state. This guarantees that frame rendering cycles (60Hz/120Hz) are never overwhelmed by non-visual intermediary state mutations.
globs: **/commonMain/**/presentation/**/*.kt, **/commonMain/**/viewmodel/**/*.kt, **/commonMain/**/*ViewModel.kt, **/commonMain/**/*StateHolder.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-stateflow-recomposition-debounce-barrier"
---

# KMP StateFlow Telemetry Debounce & Conflation Barrier for Declarative UI

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Binding Unbounded High-Frequency Telemetry Flows Directly to UI StateFlows Without Conflation Barriers

## System Constraints
You are a Principal Mobile Architect enforcing Kotlin Multiplatform (KMP) concurrency invariants. Mandate that all raw hardware telemetry, sensor streams, and high-frequency WebSocket updates pass through a sampling/conflation barrier before surfacing as shared StateFlow UI state. Prevent Compose recomposition loops and SwiftUI body invalidation starvation by strictly decoupling background data throughput from the platform main-thread rendering cadence.

## Strict Guidelines
- Engineers MUST ALWAYS isolate high-frequency telemetry ingestion flows on `Dispatchers.Default` and apply `.conflate()` or `.sample(windowMillis)` before exposing data via `stateIn`.
- Engineers MUST NOT bind raw sensor, BLE, or socket event streams directly to a `MutableStateFlow` consumed by declarative UI layers in Compose or SwiftUI.
- Code SHOULD enforce a minimum 16ms to 33ms sampling window (30fps - 60fps ceiling) for continuous numeric/spatial telemetry intended solely for UI presentation.
- Services MUST process lossless telemetry records on dedicated background coroutine scopes independent of presentation state holders.
- Components NEVER collect unthrottled shared StateFlows on `Dispatchers.Main` without an upstream throttle or conflate operator.

## Bad vs Good Implementations
### KMP Telemetry Flow Conflation and Sampling Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly mapping high-frequency hardware packets into a StateFlow without rate-limiting causes downstream Compose recomposition and SwiftUI body re-evaluation for every packet, easily exceeding the 60Hz/120Hz display refresh budget and blocking the main dispatch loop.
```kotlin
class TelemetryViewModel(
    private val bleDeviceManager: BleDeviceManager,
    private val viewModelScope: CoroutineScope
) {
    // ANTI-PATTERN: Raw 120Hz+ BLE packets piped directly to UI StateFlow.
    // Triggers severe main-thread UI jank and Compose/SwiftUI frame drops.
    val uiState: StateFlow<DeviceMetricsUiState> = bleDeviceManager.rawPacketFlow
        .map { packet -> 
            DeviceMetricsUiState(
                powerLevel = packet.readPower(),
                voltage = packet.readVoltage(),
                timestamp = packet.timestamp
            )
        }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = DeviceMetricsUiState.EMPTY
        )
}
```

#### Production Standard (Correct)
> **Standard**: By explicitly applying `.flowOn(Dispatchers.Default)`, `.sample(UI_RENDER_THROTTLE_MS)`, and `.conflate()`, packet bursts are batched and downsampled before mutating `uiState`. Declarative UI runtimes observe state changes aligned with display render limits, preventing frame drops and main-thread starvation.
```kotlin
class TelemetryViewModel(
    private val bleDeviceManager: BleDeviceManager,
    private val viewModelScope: CoroutineScope
) {
    companion object {
        private const val UI_RENDER_THROTTLE_MS = 33L // Max ~30fps for human visual perception
    }

    // PRODUCTION INVARIANT: Ingest on background dispatcher, sample/conflate,
    // and project only visually necessary updates to the declarative UI layer.
    @OptIn(FlowPreview::class)
    val uiState: StateFlow<DeviceMetricsUiState> = bleDeviceManager.rawPacketFlow
        .flowOn(Dispatchers.Default)
        .sample(UI_RENDER_THROTTLE_MS)
        .conflate()
        .map { packet ->
            DeviceMetricsUiState(
                powerLevel = packet.readPower(),
                voltage = packet.readVoltage(),
                timestamp = packet.timestamp
            )
        }
        .flowOn(Dispatchers.Default)
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = DeviceMetricsUiState.EMPTY
        )
}
```

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 StateFlow Telemetry Debounce & Conflation Barrier for Declarative UI

KMP StateFlow Telemetry Debounce & Conflation Barrier for Declarative UI defines an industrial-grade behavioral standard for mobile engineering. High-frequency streaming inputs (e.g., BLE packets, GPS fixes, sensor feeds, audio telemetry) emitted directly into shared Kotlin Multiplatform StateFlow pipelines saturate the main UI thread in Jetpack Compose and SwiftUI. Shared ViewModels must enforce a conflation and temporal sampling barrier on Dispatchers.Default before exposing UI state. This guarantees that frame rendering cycles (60Hz/120Hz) are never overwhelmed by non-visual intermediary state mutations. 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: Binding Unbounded High-Frequency Telemetry Flows Directly to UI StateFlows Without Conflation Barriers 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 DriftBinding Unbounded High-Frequency Telemetry Flows Directly to UI StateFlows Without Conflation BarriersCritical
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 isolate high-frequency telemetry ingestion flows on `Dispatchers.Default` and apply `.conflate()` or `.sample(windowMillis)` before exposing data via `stateIn`.

Engineers MUST ALWAYS isolate high-frequency telemetry ingestion flows on `Dispatchers.Default` and apply `.conflate()` or `.sample(windowMillis)` before exposing data via `stateIn`.

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 bind raw sensor, BLE, or socket event streams directly to a `MutableStateFlow` consumed by declarative UI layers in Compose or SwiftUI.

Engineers MUST NOT bind raw sensor, BLE, or socket event streams directly to a `MutableStateFlow` consumed by declarative UI layers in Compose or SwiftUI.

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 SHOULD enforce a minimum 16ms to 33ms sampling window (30fps - 60fps ceiling) for continuous numeric/spatial telemetry intended solely for UI presentation.

Code SHOULD enforce a minimum 16ms to 33ms sampling window (30fps - 60fps ceiling) for continuous numeric/spatial telemetry intended solely for UI presentation.

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 MUST process lossless telemetry records on dedicated background coroutine scopes independent of presentation state holders.

Services MUST process lossless telemetry records on dedicated background coroutine scopes independent of presentation state holders.

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 unthrottled shared StateFlows on `Dispatchers.Main` without an upstream throttle or conflate operator.

Components NEVER collect unthrottled shared StateFlows on `Dispatchers.Main` without an upstream throttle or conflate operator.

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 StateFlow Telemetry Debounce & Conflation Barrier for Declarative UI critical for AI coding assistants?

High-frequency streaming inputs (e.g., BLE packets, GPS fixes, sensor feeds, audio telemetry) emitted directly into shared Kotlin Multiplatform StateFlow pipelines saturate the main UI thread in Jetpack Compose and SwiftUI. Shared ViewModels must enforce a conflation and temporal sampling barrier on Dispatchers.Default before exposing UI state. This guarantees that frame rendering cycles (60Hz/120Hz) are never overwhelmed by non-visual intermediary state mutations. 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 (Binding Unbounded High-Frequency Telemetry Flows Directly to UI StateFlows Without Conflation Barriers) 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