kotlin-flow-state-event-modeling

chrisbanes/skills

Состояние и события в Kotlin Flow: StateFlow, SharedFlow, Channel и stateIn.

Звёзды1 162
Авторchrisbanes

Установка

SKILL.md

Kotlin Flow: state and event modeling

Core principle

Pick the primitive that matches replay, fan-out, and synchronous-read requirements. StateFlow, SharedFlow, Channel-backed flows, and cold Flow differ in buffering, who sees each emission, and whether .value exists. Wrong choices drop events, leak sharing coroutines, or force fake domain sentinels into state.

When to use this skill

You're writing or reviewing Kotlin code involving:

  • MutableStateFlow<T>(SomeSentinel) — NoUser, Empty, Loading, etc. — because the real value is async
  • .stateIn(...) called inside a function rather than assigned to a property
  • SharingStarted.WhileSubscribed(...) on a flow whose .value is read synchronously and must stay fresh
  • MutableSharedFlow for navigation events, snackbars, or other one-shot emissions where loss would be a bug
  • .map { } on a StateFlow when consumers still need synchronous .value
  • MutableStateFlow.value = _state.value.copy(...) or update code that builds expensive objects inside update { ... }

SharedFlow for single-consumer fire-once events

SharedFlow defaults have no replay buffer. If nothing is collecting at the exact instant of emission, the event is gone. For a single UI consumer handling exactly-once events such as navigation or snackbars, a buffered Channel exposed as a Flow often matches the semantics better:

// ❌ BAD
private val _navEvents = MutableSharedFlow<NavigationEvent>()
val navEvents: SharedFlow<NavigationEvent> = _navEvents.asSharedFlow()

// ✅ GOOD
private val _navEvents = Channel<NavigationEvent>(Channel.BUFFERED)
val navEvents: Flow<NavigationEvent> = _navEvents.receiveAsFlow()

Channel.receiveAsFlow() is fan-out, not broadcast: with multiple collectors, each event is delivered to one collector. Channel.BUFFERED is bounded, so sends can suspend and trySend can fail. If multiple observers must all see the same event, use explicit state, durable storage, or a deliberately configured SharedFlow instead.

StateFlow polluted with invalid sentinel defaults

StateFlow forces an initial value. When the real value is async, developers sometimes invent fake domain values — NoUser, EmptyUser, placeholder IDs — and every consumer is forced to treat that sentinel as real data.

// ❌ BAD — sentinel leaks into the type
class UserSession(private val db: Db) {
    private val _user = MutableStateFlow<User>(NoUser)
    val user: StateFlow<User> = _user.asStateFlow()
    init { scope.launch { _user.value = db.load() } }
}

One fix is phasing: don't expose the StateFlow until the real value exists.

// ✅ GOOD — bootstrap suspends; observers only see real users
class UserSession(private val db: Db) {
    private var _user: MutableStateFlow<User>? = null
    val user: StateFlow<User>
        get() = checkNotNull(_user) { "Call login() first" }

    suspend fun login() {
        _user = MutableStateFlow(db.load())
    }
}

If absence, loading, or error is a real state, model it explicitly (User?, sealed interface UserUiState, Result, etc.). The bug is a fake domain value masquerading as real data, not every initial value.

Mutate MutableStateFlow with update { ... }

Prefer MutableStateFlow.update { current -> ... } over reading .value and writing it back. update applies the transform atomically against the latest state, which avoids lost updates when multiple coroutines mutate the same state.

// BAD — read/modify/write can lose concurrent updates.
_state.value = _state.value.copy(
    selectedId = id,
    details = details,
)

// GOOD — transform starts from the latest state.
_state.update { current ->
    current.copy(
        selectedId = id,
        details = details,
    )
}

Keep object creation outside the update block unless it needs the current state. The update lambda can be retried, so expensive work or side effects inside it may run more than once:

// GOOD — details does not depend on current state, so build it once.
val details = Details.from(response)
_state.update { current ->
    current.copy(details = details)
}

// GOOD — derived value depends on current state, so compute it inside.
_state.update { current ->
    val nextItems = current.items.replaceById(updatedItem)
    current.copy(items = nextItems)
}

The block should be a pure, fast state transformation: no network calls, database writes, logging side effects, random IDs, or time reads unless those values were captured before the block.

stateIn() inside a function

// ❌ BAD — new sharing coroutine every call
fun getPreferences(): StateFlow<Prefs> =
    repo.prefsFlow.stateIn(scope, SharingStarted.Eagerly, Prefs.Default)

Every call to getPreferences() launches a fresh coroutine on scope that never completes. Performance dies fast under repeated reads.

// ✅ GOOD — one shared instance, computed once
val preferences: StateFlow<Prefs> =
    repo.prefsFlow.stateIn(viewModelScope, SharingStarted.Eagerly, Prefs.Default)

WhileSubscribed with synchronous .value

SharingStarted.WhileSubscribed(timeout) disconnects the upstream when there are no active collectors. While disconnected, .value returns the last cached value, which may be stale or still the initial value.

Rule: if .value must be fresh or initialized without an active collector, use SharingStarted.Eagerly or explicit initialization. WhileSubscribed is fine when stale/cached values are acceptable and consumers primarily collect asynchronously.

.map on StateFlow loses .value

// ❌ BAD — `name.value` won't compile; it's now a plain Flow
val name: Flow<String> = userState.map { it.name }

If you need synchronous .value, terminate the chain with .stateIn(...):

// ✅ GOOD
val name: StateFlow<String> = userState
    .map { it.name }
    .stateIn(viewModelScope, SharingStarted.Eagerly, userState.value.name)

Community “derived state flow” utilities run the transform on every .value read — only acceptable for fast, idempotent transforms. Default to .stateIn(...).

Decision: which Flow type?

NeedPrimitive
State that always has a value, read by both async collectors and synchronous codeStateFlow, often with SharingStarted.Eagerly when .value matters
Hot stream, multiple subscribers, no requirement for synchronous .valueSharedFlow
Discrete events for one consumer, exactly-once handoffConsider Channel(BUFFERED).receiveAsFlow()
Cold stream, one consumer per collectionPlain Flow

If you're tempted to reach for SharedFlow, ask: would dropping an emission be a bug, and how many consumers must see it? If one consumer must handle it exactly once, a Channel may fit. If every observer must see it, model durable state or configure a broadcast stream deliberately.

Quick reference

SymptomProblemFix
MutableStateFlow<X>(FakeDomainValue)Invalid placeholder defaultModel absence explicitly or use phase initialization
MutableSharedFlow<Event> for single-consumer nav/snackbarLossy default event streamConsider Channel(BUFFERED).receiveAsFlow()
fun foo() = flow.stateIn(...)Per-call sharing coroutineMake it a val / shared instance
WhileSubscribed + .value must be fresh/initializedStale or initial dataSharingStarted.Eagerly or explicit initialization
stateFlow.map { ... } consumed as stateLost .valueTerminate with .stateIn(...)
_state.value = _state.value.copy(...)Non-atomic read/modify/write_state.update { it.copy(...) }
Expensive object creation inside update { ... } that doesn't use current stateWork can repeat if update retriesBuild before update; keep only current-state transforms inside

Red flags during review

ThoughtReality
"We need SharedFlow because there are multiple subscribers"Multiple subscribers change the semantics. Channel.receiveAsFlow() is not broadcast; choose the event model deliberately.
"We'll use WhileSubscribed to save resources"Only if stale/initial .value reads are acceptable. Verify before applying.
"I'll use a sentinel until real data loads"Consumers treat it as real domain; prefer explicit UI/state modeling or phasing.
"I'll construct the new object inside update because it's convenient"The lambda may retry. Construct outside unless it depends on the current state.

Related

  • kotlin-control-flow — choosing when, guard conditions, exhaustiveness, smart casts, and early returns when modeling state and events.
  • kotlin-coroutines-structured-concurrency — scope ownership, init launches, fire-and-forget boundaries, cancellation, runBlocking
  • compose-side-effects — collecting event flows and wiring side effects in Compose
  • compose-state-holder-ui-split — where state holders expose flows to UI

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: kotlin-flow-state-event-modeling](https://darkplay.ru/ai/skills/chrisbanes-skills-kotlin-flow-state-event-modeling)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

mattpocock-skillsmattpocock · Агентские навыки Matt Pocock для настоящей инженерии: разбор задач, потоки спецификаций и…
41 комп.
eccaffaan-m · Нативный для harness операторский слой ECC: 67 агентов, 278 навыков, 94 шима устаревших…
441 комп.
Add Language Rulesaffaan-m · Каркас команды workflow для add-language-rules в everything-claude-code.
225 587 ★
Chief Of Staffaffaan-m · Личный руководитель коммуникаций, который сортирует почту, Slack, LINE и Messenger…
225 587 ★
Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
225 587 ★
Database Migrationaffaan-m · Каркас команды workflow для database-migration в everything-claude-code.
225 587 ★
E2e Runneraffaan-m · Специалист по E2E-тестам на Vercel Agent Browser и Playwright: генерация, запуск и…
225 587 ★
Feature Developmentaffaan-m · Каркас команды workflow для feature-development в everything-claude-code.
225 587 ★
Flutter Revieweraffaan-m · Ревьюер кода Flutter и Dart: виджеты, управление состоянием, идиомы и архитектура.
225 587 ★
Harmonyos App Resolveraffaan-m · Эксперт по HarmonyOS на ArkTS и ArkUI: состояние V2, навигация, API и производительность.
225 587 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8