# Android State

> Configure ViewModel state emission with StateFlow, SharedFlow, and sealed UiState classes in Android. Use for state modeling and sharing policies; defer generic lifecycle collection, navigation-event plumbing, Hilt injection, test code, and configuration-change recipes to their specific skills.

- Skill: `hoangnguyen0403/android-state` (Agent Skill, multi-file: 3 files)
- Install (CLI): `npx skillmds add hoangnguyen0403/android-state`
- Raw SKILL.md: https://api.skillmd.com/api/skills/hoangnguyen0403/android-state/raw
- Safety review: pending (external: skill-scanner PASS, skillspector PASS)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: HoangNguyen0403 (https://skillmd.com/u/hoangnguyen0403)
- Updated: 2026-08-19
- Page: https://skillmd.com/skills/hoangnguyen0403/android-state

---

# Android State Management

## **Priority: P0 (CRITICAL)**

## 1. Structure ViewModel

- Expose ONE `StateFlow<UiState>` via `.asStateFlow()`.
- Use `viewModelScope` for all coroutines.
- Trigger initial load in `init` block.

See [templates](references/implementation.md) for ViewModel and UiState examples.

## 2. Define UI State (LCE Pattern)

- Use sealed interface with Loading, Content, Error variants.
- Mark data classes `@Immutable`.

See [templates](references/implementation.md) for sealed UiState pattern.

## 3. Collect State Lifecycle-Safely

- Use `collectAsStateWithLifecycle()` in Compose.
- Use `SharingStarted.WhileSubscribed(5000)` for shared resources.

## Anti-Patterns

- **No LiveData for New Code**: Use StateFlow — lifecycle-safe and Compose-compatible.
- **No Public MutableStateFlow**: Expose only `.asStateFlow()` to consumers.
- **No Context in ViewModel**: Leaks Activity. Use Application context if truly needed.

## Verification

- [ ] Each ViewModel exposes exactly one `StateFlow<UiState>`.
- [ ] UiState is a sealed interface with Loading, Content, Error variants.
- [ ] UI collects with `collectAsStateWithLifecycle()`.
- [ ] `./gradlew test` passes for ViewModel tests.

## References

- [Templates](references/implementation.md)

