mmiani/kotlin-kmp-claude-agent-skills/kotlin-project-state-management

Claude Code and agent skill by mmiani/kotlin-kmp-claude-agent-skills

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Use when choosing, implementing, or reviewing state-holder patterns in a KMP project — ViewModel, shared presenter, MVI, or StateFlow-in-common — including effect handling, UiState modeling, and testability.

Install

npx vskill@latest install mmiani/kotlin-kmp-claude-agent-skills/kotlin-project-state-management

SKILL.md

Kotlin Multiplatform State Management

Use this skill when choosing, implementing, or reviewing how UI state is owned and produced in a Kotlin Multiplatform project.

State management sits at the intersection of every other KMP architectural concern. How state is held, where it lives in source sets, and how it integrates with each platform's lifecycle determines the testability, predictability, and long-term maintainability of the entire UI layer.

This skill is intentionally precise. It distinguishes between patterns clearly, explains when each is appropriate, and flags common mistakes that look correct at first but create problems at scale.

What this skill covers

  • The invariant state contract that all valid state-holder patterns must satisfy
  • The main pattern families available in KMP and what each costs
  • Platform-specific differences that affect state-holder choice
  • Effect handling: one-time events vs persistent state
  • State modeling: how to shape UiState correctly
  • Testability implications of each choice
  • Anti-patterns in each category

What this skill does not cover

  • Navigation (see kotlin-navigation-compose-multiplatform)
  • Data-layer design (see kotlin-data-kmp-data-layer)
  • Full architecture review (see kotlin-project-architecture-review)
  • Full feature implementation (see kotlin-project-feature-implementation)

The state-holder contract

Regardless of which pattern a project uses, a valid state holder must satisfy this contract:

  1. One observable state output — a single stream of immutable UiState that the UI renders from. Not several scattered booleans, not a mutable object the UI reads fields from directly.
  2. Separate one-time effects — navigation triggers, snackbar requests, permission launches, and similar one-shot actions must not be modeled as persistent state. Once consumed, they must not replay.
  3. User actions as inputs — the UI sends events or calls action functions; it does not set state directly or coordinate work.
  4. No business rules in rendering — the state holder processes inputs, coordinates lower layers, and produces output. Composables render.
  5. Platform lifecycle transparency — the state holder must behave correctly across the platform lifecycle events relevant to its target (configuration changes on Android, view disappear/appear on iOS, window focus on desktop).

Every pattern described below is evaluated against this contract.


Pattern families

1. Android ViewModel with StateFlow (Android-only or Android-primary)

What it is: ViewModel from AndroidX lifecycle, holding a MutableStateFlow<UiState> privately and exposing it as StateFlow<UiState>. Effects emitted via a separate SharedFlow or Channel-backed flow.

When it is the right choice:

  • The project targets Android only, or Android plus other platforms where ViewModel wrapper libraries are used
  • The team is already fluent with ViewModel semantics
  • Jetpack Compose with collectAsStateWithLifecycle() or collectAsState() is the rendering layer

What it provides:

  • Automatic scoping to Android's ViewModel lifecycle (survives configuration changes by default via viewModelScope)
  • Strong Jetpack integration (hiltViewModel(), Navigation ViewModel scoping, SavedStateHandle)
  • Well-understood by Android developers

Platform constraint: ViewModel is an AndroidX library. It does not exist natively on iOS, desktop, or web. Projects using ViewModel in shared commonMain code require an additional library to provide a ViewModel-compatible abstraction on non-Android targets (see KMP ViewModel libraries below).

Source-set placement:

  • Pure Android ViewModel implementations belong in androidMain
  • If the project uses a KMP ViewModel abstraction, the shared interface can live in commonMain

Testability:

  • Good: can be tested on JVM with kotlinx-coroutines-test, TestScope, runTest, and Turbine or collectValues()
  • viewModelScope must be replaced with an injected CoroutineScope in tests, or use the ViewModelScenario/rule pattern from lifecycle-viewmodel-testing

2. Shared presenter / state machine in commonMain

What it is: A plain Kotlin class in commonMain that holds a MutableStateFlow<UiState> and exposes it, processes user actions via functions or a sealed Action type, and emits effects. No AndroidX dependency. Lifecycle management is the platform entry point's responsibility.

When it is the right choice:

  • The project targets multiple platforms and wants state-holder logic to be shared and tested once
  • The team wants to avoid a dependency on AndroidX ViewModel in shared code
  • The shared Kotlin logic is already substantial enough that platform-specific state holders would duplicate significant logic

What it provides:

  • Fully testable in commonTest with kotlin.test and kotlinx-coroutines-test
  • No platform dependency — compiles for all KMP targets
  • Explicit lifecycle management (no magic — the platform entry point starts and cancels the scope)

Platform responsibility: The presenter owns no lifecycle. Each platform must:

  • Create the presenter at the right point in the view lifecycle
  • Provide a CoroutineScope that is cancelled when the view is gone
  • Cancel the scope correctly on back navigation or view destruction
  • Handle process death / state restoration separately if needed (there is no SavedStateHandle equivalent without explicit implementation)

On Android, this usually means creating the presenter inside a ViewModel to retain it across configuration changes, then delegating to it. On iOS, this means creating the presenter in the view owner (e.g., ObservableObject-wrapping in SwiftUI or direct state subscription in UIKit) and tying its scope to the view's lifetime.

Source-set placement:

  • Presenter class: commonMain
  • Platform lifecycle wiring: androidMain, iosMain, etc.
  • Tests: commonTest

Testability:

  • Excellent: all state-transition logic testable in commonTest with no Android dependency
  • Coroutine scope injection makes deterministic testing straightforward

3. KMP ViewModel abstraction libraries

What it is: Third-party or JetBrains-supported libraries that provide a ViewModel class in commonMain that compiles to AndroidX ViewModel on Android and to a lifecycle-aware equivalent on other targets.

As of mid-2025, the main options are:

  • `lifecycle-viewmodel` KMP artifact (from AndroidX/JetBrains): JetBrains introduced official KMP support for androidx.lifecycle.ViewModel as a multiplatform artifact. This is the most official path when it matches the project's target set.
  • Third-party ViewModel abstractions: several community libraries provide similar functionality; evaluate for stability, maintenance, and target support before adopting.

When it is the right choice:

  • The project wants to write ViewModel-style code once in commonMain and have it behave correctly on all targets including Android
  • The team does not want to manage lifecycle wiring manually per platform
  • The lifecycle-viewmodel KMP artifact covers the project's targets

What it provides:

  • Shared ViewModel in commonMain with lifecycle-correct behavior per platform
  • viewModelScope (or equivalent) provided per-platform
  • Familiar ViewModel API surface

What to verify:

  • Target coverage: confirm the chosen artifact supports all declared KMP targets
  • API stability: check current release status — KMP ViewModel support matured significantly in 2024–2025 but verify against current AndroidX release notes
  • SavedStateHandle availability: may not be supported on non-Android targets; check per-library docs

Source-set placement:

  • ViewModel classes: commonMain
  • Platform-specific lifecycle wiring (if any): platform source sets

Testability:

  • Similar to shared presenter: use injected scopes and kotlinx-coroutines-test in commonTest
  • Avoid testing through AndroidX test infrastructure if the goal is shared test coverage

4. MVI (Model-View-Intent) pattern

What it is: A stricter unidirectional architecture where user actions are explicitly typed as Intent or Action objects, the state holder reduces them into new State objects (often via a pure function or a reducer), and side effects are modeled explicitly as an Effect or SideEffect type.

MVI is a pattern, not a library. It can be implemented on top of any of the above state-holder mechanisms. Several community libraries (Orbit MVI, MVI Kotlin, etc.) provide MVI structure as a framework.

When it is the right choice:

  • Screens have complex, non-trivial state transitions where the action → state relationship benefits from being an explicit, traceable function
  • The team wants stricter discipline on what can cause a state change
  • Testing with explicit action/state pairs (action X in current state S produces state S') is valuable for the use case

When it is likely overkill:

  • Simple screens with few states (loading/success/error) — the overhead of action types and reducers exceeds the complexity
  • Small teams or fast-moving projects where ceremony slows iteration more than it helps

What it provides:

  • Highly deterministic state transitions
  • Explicit, auditable action log
  • Effects (one-time events) are a first-class concern in most MVI implementations
  • Straightforward to test at the reducer level with pure functions

What to watch:

  • Action type proliferation: large screens can accumulate dozens of action subtypes, making the sealed class unwieldy
  • Effect vs state confusion still occurs even with MVI — a one-time navigation trigger modeled as persistent state is wrong regardless of the pattern name
  • Library choice matters for KMP: verify the chosen MVI library supports your full target set

Source-set placement:

  • If using a KMP-compatible MVI library: state holder and reducer in commonMain
  • Platform wiring as needed in platform source sets

Effect handling

One-time effects are the most common source of state-management bugs. The core mistake is modeling an effect as persistent state.

The problem
kotlin
// WRONG: snackbar as persistent state
data class UiState(
val items: List<Item>,
val errorMessage: String? // stays in state after being shown — shows again on recomposition
)

A user sees the snackbar. They rotate the screen. The state is re-collected. The snackbar shows again. The error message is now part of permanent UI state and will survive any state restoration.

Correct approaches

Option A: Separate `SharedFlow` for effects

kotlin
// State holds only persistent UI truth
data class UiState(val items: List<Item>, val isLoading: Boolean)
// Effects are fire-and-forget
sealed interface UiEffect {
data class ShowError(val message: String) : UiEffect
data object NavigateToDetail : UiEffect
}
val uiState: StateFlow<UiState>
val effects: SharedFlow<UiEffect> // replay = 0

The SharedFlow with replay = 0 emits once to current subscribers. No replay on new subscription. UI collects this in a LaunchedEffect keyed to the composable lifecycle.

Option B: Nullable one-time event in state with explicit consumption Some teams model effects as nullable fields with an explicit "consumed" action. This works but requires discipline — forgetting to send the consumed action is a common mistake.

Option C: `Channel`-backed flow (FIFO queue) A Channel(BUFFERED) exposed as a receiveAsFlow() delivers effects one at a time to one subscriber. Good for effects that must not be dropped even during lifecycle transitions, but adds buffering complexity.

Review rule: Every non-null, non-boolean field in UiState that represents an action rather than a fact is likely a misplaced effect. Ask: "If this screen is recreated, should this still be shown?" If no, it is an effect.


This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/mmiani/kotlin-kmp-claude-agent-skills/kotlin-project-state-management/badge)](https://verified-skill.com/skills/mmiani/kotlin-kmp-claude-agent-skills/kotlin-project-state-management)

Something wrong with this skill or its page? Tell us.