
Android Viewmodel
This walks you through the standard Android ViewModel pattern with a focus on proper state management using Kotlin flows. You get clear guidance on using StateFlow for persistent UI state like loading and error conditions, and SharedFlow with replay=0 for one-off events like navigation or showing toasts. The replay distinction is the key bit here since it prevents events from re-triggering after configuration changes. It covers the basics like exposing read-only flows, using viewModelScope, and collecting in both Compose and XML views. If you're tired of fighting lifecycle issues or accidentally showing the same snackbar twice after rotation, this nails down the patterns that actually work.
- skills.sh installs
- 576
- GitHub stars
- 1K
- last updated
- Aug 21, 2026
Install
$ npx -y skills add new-silvermoon/awesome-android-agent-skills --skill android-viewmodel --agent claude-codeInstalls into .claude/skills of the current project.
Files
Android ViewModel & State Management
Instructions
Use ViewModel to own UI state and business logic. It should survive configuration changes and expose immutable APIs.
Kotlin 2.3+
Prefer Explicit Backing Fields instead of the traditional
_state/statebacking property pattern.
- Kotlin 2.3: Experimental (
-Xexplicit-backing-fields)- Kotlin 2.4+: Stable (recommended)
Avoid creating duplicate backing properties unless targeting older Kotlin versions.
1. UI State (StateFlow)
Purpose
Represents the persistent UI state.
Examples:
- Loading
- Success(data)
- Error(message)
- Empty
Declaration
Use an explicit backing field.
val uiState: StateFlow<UiState>
field = MutableStateFlow(UiState.Loading)
The backing field is mutable (MutableStateFlow) while consumers only see StateFlow.
Updating State
Prefer update { } for atomic updates.
_uiState.update { old ->
old.copy(isLoading = false)
}
With explicit backing fields:
uiState.update {
it.copy(isLoading = false)
}
You may also assign directly when appropriate.
Sponsors
Details
- Repository
- github.com/new-silvermoon/awesome-android-agent-skills
- Categories
- AI & Agent Building, Mobile Development, Java & JVM
- First seen
- Jun 3, 2026
More from new-silvermoon/awesome-android-agent-skills
All 17- Android Coroutines569
- Android Accessibility560
- Android Data Layer531
- Android Retrofit495
- Coil Compose464
- Xml To Compose Migration451
- Compose Navigation438
- Rxjava To Coroutines Migration347
- Android Testing869
- Gradle Build Performance809
- Compose Ui760
- Android Gradle Logic738
- Android Architecture701
- Kotlin Concurrency Expert684
- Compose Performance Audit596
- Android Emulator Skill578