AI agent skill · by @HoangNguyen0403
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.
Archived 2026-10-23 · Source updated 2026-09-15 · License: MIT. Check the original repository for the latest version.
SKILL.md instructions
# 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)