This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: cmp-18-retained-state-lifecycle-isolation

Compose Multiplatform 1.8 Retained State Lifecycle Isolation Across iOS/Android Boundaries

Enforces deterministic lifecycle bounds and memory isolation for retained ViewModels and coroutine scopes in Compose Multiplatform 1.8. Prevents native iOS UIViewController deallocation leaks and Android backstack desynchronization caused by unmanaged multiplatform state holders.

Prohibited Anti-Pattern: Global Retained State Capturing Native Lifecycle Roots Causing iOS UIViewController Memory Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform 1.8 Retained State Lifecycle Isolation Across iOS/Android Boundaries - Enforces deterministic lifecycle bounds and memory isolation for retained ViewModels and coroutine scopes in Compose Multiplatform 1.8. Prevents native iOS UIViewController deallocation leaks and Android backstack desynchronization caused by unmanaged multiplatform state holders.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, **/androidMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/cmp-18-retained-state-lifecycle-isolation"
---

# Compose Multiplatform 1.8 Retained State Lifecycle Isolation Across iOS/Android Boundaries

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Global Retained State Capturing Native Lifecycle Roots Causing iOS UIViewController Memory Leaks

## System Constraints
You are a Principal Mobile Architect enforcing Compose Multiplatform 1.8 Retained State Lifecycle Isolation. You must ensure that all ViewModels and retained state containers use CMP 1.8's androidx.lifecycle abstractions, guaranteeing that state is tied exclusively to the platform-agnostic NavigationBackStackEntry or parent LifecycleOwner. You must prevent any direct references to iOS UIViewController, native platform contexts, or unbounded coroutine scopes from being retained across navigation transitions and platform teardown events.

## Strict Guidelines
- Engineers MUST ALWAYS instantiate retained ViewModels using `androidx.lifecycle.viewmodel.compose.viewModel()` bound to the current `NavBackStackEntry` or `LocalLifecycleOwner`.
- Engineers MUST NOT store platform-specific reference types (such as `UIViewController`, `Context`, or native platform delegates) inside retained `ViewModel` instances or `rememberSaveable` state bundles.
- Code SHOULD leverage Compose Multiplatform 1.8 `LifecycleEventEffect` or `LifecycleStartEffect` instead of raw `DisposableEffect` for native lifecycle observation.
- Services MUST clear async jobs and observable streams via `ViewModel.viewModelScope` to ensure automatic cancellation when `ComposeUIViewController` pops off the iOS `UINavigationController` stack.
- Components NEVER bridge iOS `ComposeUIViewController` without explicitly handling lifecycle synchronization via standard Jetpack Compose navigation or passing root lifecycle termination hooks.

## Bad vs Good Implementations
### Retained State and Native Controller Lifecycle Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Storing platform-specific instances (UIViewController) inside retained or remembered objects captures the native controller reference. When popped from iOS UINavigationController, Compose does not automatically invalidate or dispose this reference, creating an uncollectible native memory leak.
```kotlin
// Anti-Pattern: Unmanaged retained state capturing native controller references
// Survives UIViewController deallocation on iOS, creating severe memory retention cycles

import androidx.compose.runtime.*
import platform.UIKit.UIViewController

class BadOrderViewModel(val platformController: UIViewController?) {
    var isProcessing by mutableStateOf(false)
    // Global memory leak: UIViewController is captured forever
}

@Composable
fun OrderScreen(controller: UIViewController?) {
    // Incorrect: remember keeps instance alive across composition without lifecycle disposal
    val viewModel = remember {
        BadOrderViewModel(platformController = controller)
    }
    
    DisposableEffect(Unit) {
        onDispose {
            // Fails to notify or clear ViewModel state when navigation pops on iOS
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Using CMP 1.8's standard `viewModel()` factory links the ViewModel directly to Jetpack Lifecycle primitives. Coroutines run strictly within `viewModelScope`, and the instance is deterministically disposed via `onCleared()` upon navigation backstack removal, completely isolated from native UIViewController lifecycles.
```kotlin
// Production Standard: CMP 1.8 Lifecycle-aware retained state with ViewModelScope isolation

import androidx.compose.runtime.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.LifecycleStartEffect
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

class OrderViewModel : ViewModel() {
    private val _isProcessing = MutableStateFlow(false)
    val isProcessing: StateFlow<Boolean> = _isProcessing.asStateFlow()
    
    // Platform-agnostic business logic. Cleared automatically via onCleared() when popped.
    override fun onCleared() {
        super.onCleared()
    }
}

@Composable
fun OrderScreen(
    viewModel: OrderViewModel = viewModel { OrderViewModel() },
    onNavigateBack: () -> Unit
) {
    val isProcessing by viewModel.isProcessing.collectAsState()
    
    // CMP 1.8 standard: explicit lifecycle-bound observers without native captures
    LifecycleStartEffect(viewModel) {
        onStopOrDispose {
            // Deterministically pause or unbind when view goes to background or navigation pops
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Compose Multiplatform 1.8 Retained State Lifecycle Isolation Across iOS/Android Boundaries

Compose Multiplatform 1.8 Retained State Lifecycle Isolation Across iOS/Android Boundaries defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic lifecycle bounds and memory isolation for retained ViewModels and coroutine scopes in Compose Multiplatform 1.8. Prevents native iOS UIViewController deallocation leaks and Android backstack desynchronization caused by unmanaged multiplatform state holders. 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: Global Retained State Capturing Native Lifecycle Roots Causing iOS UIViewController Memory Leaks 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 DriftGlobal Retained State Capturing Native Lifecycle Roots Causing iOS UIViewController Memory LeaksCritical
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 instantiate retained ViewModels using `androidx.lifecycle.viewmodel.compose.viewModel()` bound to the current `NavBackStackEntry` or `LocalLifecycleOwner`.

Engineers MUST ALWAYS instantiate retained ViewModels using `androidx.lifecycle.viewmodel.compose.viewModel()` bound to the current `NavBackStackEntry` or `LocalLifecycleOwner`.

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 store platform-specific reference types (such as `UIViewController`, `Context`, or native platform delegates) inside retained `ViewModel` instances or `rememberSaveable` state bundles.

Engineers MUST NOT store platform-specific reference types (such as `UIViewController`, `Context`, or native platform delegates) inside retained `ViewModel` instances or `rememberSaveable` state bundles.

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 leverage Compose Multiplatform 1.8 `LifecycleEventEffect` or `LifecycleStartEffect` instead of raw `DisposableEffect` for native lifecycle observation.

Code SHOULD leverage Compose Multiplatform 1.8 `LifecycleEventEffect` or `LifecycleStartEffect` instead of raw `DisposableEffect` for native lifecycle observation.

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 clear async jobs and observable streams via `ViewModel.viewModelScope` to ensure automatic cancellation when `ComposeUIViewController` pops off the iOS `UINavigationController` stack.

Services MUST clear async jobs and observable streams via `ViewModel.viewModelScope` to ensure automatic cancellation when `ComposeUIViewController` pops off the iOS `UINavigationController` stack.

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 bridge iOS `ComposeUIViewController` without explicitly handling lifecycle synchronization via standard Jetpack Compose navigation or passing root lifecycle termination hooks.

Components NEVER bridge iOS `ComposeUIViewController` without explicitly handling lifecycle synchronization via standard Jetpack Compose navigation or passing root lifecycle termination hooks.

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 1.8 Retained State Lifecycle Isolation Across iOS/Android Boundaries critical for AI coding assistants?

Enforces deterministic lifecycle bounds and memory isolation for retained ViewModels and coroutine scopes in Compose Multiplatform 1.8. Prevents native iOS UIViewController deallocation leaks and Android backstack desynchronization caused by unmanaged multiplatform state holders. 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 (Global Retained State Capturing Native Lifecycle Roots Causing iOS UIViewController Memory Leaks) 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