This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kotlin-k2-coroutine-scope-lifecycle-invariants

Kotlin 2.0 K2 Coroutine Scope Disposal and Structured Concurrency

Enforces strict structured concurrency in Jetpack Compose and ViewModel architectures under Kotlin 2.0 K2. Mandates explicit scope lifecycle management, prevents orphaned jobs across recompositions, enforces safe StateFlow sharing with SharingStarted.WhileSubscribed(5000), and eliminates GlobalScope and unconstrained CoroutineScope leaks.

Prohibited Anti-Pattern: Unbounded Job Spawning, GlobalScope Leaks, and Active Flow Upstreams in Dead ViewModels or Detached Composables

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin 2.0 K2 Coroutine Scope Disposal and Structured Concurrency - Enforces strict structured concurrency in Jetpack Compose and ViewModel architectures under Kotlin 2.0 K2. Mandates explicit scope lifecycle management, prevents orphaned jobs across recompositions, enforces safe StateFlow sharing with SharingStarted.WhileSubscribed(5000), and eliminates GlobalScope and unconstrained CoroutineScope leaks.
globs: **/*.kt, **/*.kts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kotlin-k2-coroutine-scope-lifecycle-invariants"
---

# Kotlin 2.0 K2 Coroutine Scope Disposal and Structured Concurrency

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Job Spawning, GlobalScope Leaks, and Active Flow Upstreams in Dead ViewModels or Detached Composables

## System Constraints
You are a Principal Android Architect enforcing strict structured concurrency under Kotlin 2.0 (K2 compiler). Reject any code that bypasses lifecycle-aware scopes, risks memory leaks via unconstrained CoroutineScope instances, neglects the 5-second WhileSubscribed buffer on state flows, or launches unmanaged jobs inside Composable functions.

## Strict Guidelines
- Engineers MUST ALWAYS use `viewModelScope` for ViewModel operations and bound Composable scopes (`LaunchedEffect`, `rememberCoroutineScope`) for UI-driven effects.
- Engineers MUST NOT instantiate unmanaged `CoroutineScope(Dispatchers.Main)` or use `GlobalScope` anywhere in application or library code.
- Code SHOULD ALWAYS use `SharingStarted.WhileSubscribed(5_000)` when converting cold flows to `StateFlow` via `stateIn` to withstand configuration changes without leaking upstream collection.
- Services MUST cancel and join active child jobs explicitly using cooperative cancellation (`ensureActive()` or `yield()`) inside long-running loops.
- Components NEVER trigger side effects via `CoroutineScope.launch` during initial Composable execution; engineers MUST route all composition-bound asynchronous jobs through `LaunchedEffect(key)`.

## Bad vs Good Implementations
### ViewModel StateFlow Sharing and Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: GlobalScope causes unbounded memory leaks and prevents cancellation when the screen is dismissed. SharingStarted.Eagerly keeps the upstream database or network stream active perpetually, draining battery and memory.
```kotlin
class UserViewModel(private val repository: UserRepository) : ViewModel() {
    // ANTI-PATTERN: Eagerly started or Lazily started StateFlow leaks upstream flow
    // when ViewModel is backgrounded or Composable is not collecting.
    // GlobalScope causes orphaned jobs that bypass ViewModel lifecycle.
    val uiState: StateFlow<UserState> = repository.observeUser()
        .stateIn(
            scope = GlobalScope,
            started = SharingStarted.Eagerly,
            initialValue = UserState.Loading
        )

    fun refresh() {
        // Unmanaged CoroutineScope ignores ViewModel onCleared cancellation
        CoroutineScope(Dispatchers.IO).launch {
            repository.fetchRemoteUser()
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Leverages viewModelScope for automatic cancellation during ViewModel teardown. Uses SharingStarted.WhileSubscribed(5_000) to allow a 5-second grace period across activity recreation (e.g., screen rotation) before stopping upstream emissions.
```kotlin
class UserViewModel(private val repository: UserRepository) : ViewModel() {
    // PRODUCTION INVARIANT: Bound to viewModelScope with 5-second buffer
    // to survive configuration changes without restarting upstream cold flows.
    val uiState: StateFlow<UserState> = repository.observeUser()
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = UserState.Loading
        )

    fun refresh() {
        // Bound to viewModelScope: Automatically cancelled when ViewModel is cleared
        viewModelScope.launch {
            repository.fetchRemoteUser()
        }
    }
}
```

### Composable Side-Effect Lifecycle Binding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling scope.launch directly inside the Composable function body triggers a new uncancelled coroutine on every single recomposition, resulting in race conditions and severe thread pool starvation.
```kotlin
@Composable
fun ProfileScreen(userId: String, viewModel: ProfileViewModel) {
    // ANTI-PATTERN: Leaking coroutines directly in composition body
    val scope = rememberCoroutineScope()
    scope.launch {
        // Executes on EVERY recomposition, causing duplicate concurrent jobs
        viewModel.trackScreenView(userId)
    }

    Text(text = "User: $userId")
}
```

#### Production Standard (Correct)
> **Standard**: LaunchedEffect binds the coroutine's lifecycle strictly to the composition. If userId changes or the Composable leaves the composition tree, the previous coroutine job is cancelled cooperatively.
```kotlin
@Composable
fun ProfileScreen(userId: String, viewModel: ProfileViewModel) {
    // PRODUCTION INVARIANT: LaunchedEffect cancels and relaunches automatically
    // when the key (userId) changes, and cancels immediately on exit from composition.
    LaunchedEffect(userId) {
        viewModel.trackScreenView(userId)
    }

    Text(text = "User: $userId")
}
```

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 2.0 K2 Coroutine Scope Disposal and Structured Concurrency

Kotlin 2.0 K2 Coroutine Scope Disposal and Structured Concurrency defines an industrial-grade behavioral standard for mobile engineering. Enforces strict structured concurrency in Jetpack Compose and ViewModel architectures under Kotlin 2.0 K2. Mandates explicit scope lifecycle management, prevents orphaned jobs across recompositions, enforces safe StateFlow sharing with SharingStarted.WhileSubscribed(5000), and eliminates GlobalScope and unconstrained CoroutineScope leaks. 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: Unbounded Job Spawning, GlobalScope Leaks, and Active Flow Upstreams in Dead ViewModels or Detached Composables 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 DriftUnbounded Job Spawning, GlobalScope Leaks, and Active Flow Upstreams in Dead ViewModels or Detached ComposablesCritical
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 use `viewModelScope` for ViewModel operations and bound Composable scopes (`LaunchedEffect`, `rememberCoroutineScope`) for UI-driven effects.

Engineers MUST ALWAYS use `viewModelScope` for ViewModel operations and bound Composable scopes (`LaunchedEffect`, `rememberCoroutineScope`) for UI-driven effects.

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 instantiate unmanaged `CoroutineScope(Dispatchers.Main)` or use `GlobalScope` anywhere in application or library code.

Engineers MUST NOT instantiate unmanaged `CoroutineScope(Dispatchers.Main)` or use `GlobalScope` anywhere in application or library 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.
3

Code SHOULD ALWAYS use `SharingStarted.WhileSubscribed(5_000)` when converting cold flows to `StateFlow` via `stateIn` to withstand configuration changes without leaking upstream collection.

Code SHOULD ALWAYS use `SharingStarted.WhileSubscribed(5_000)` when converting cold flows to `StateFlow` via `stateIn` to withstand configuration changes without leaking upstream collection.

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 cancel and join active child jobs explicitly using cooperative cancellation (`ensureActive()` or `yield()`) inside long-running loops.

Services MUST cancel and join active child jobs explicitly using cooperative cancellation (`ensureActive()` or `yield()`) inside long-running loops.

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 trigger side effects via `CoroutineScope.launch` during initial Composable execution

Components NEVER trigger side effects via `CoroutineScope.launch` during initial Composable execution; engineers MUST route all composition-bound asynchronous jobs through `LaunchedEffect(key)`.

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 2.0 K2 Coroutine Scope Disposal and Structured Concurrency critical for AI coding assistants?

Enforces strict structured concurrency in Jetpack Compose and ViewModel architectures under Kotlin 2.0 K2. Mandates explicit scope lifecycle management, prevents orphaned jobs across recompositions, enforces safe StateFlow sharing with SharingStarted.WhileSubscribed(5000), and eliminates GlobalScope and unconstrained CoroutineScope leaks. 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 (Unbounded Job Spawning, GlobalScope Leaks, and Active Flow Upstreams in Dead ViewModels or Detached Composables) 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