
android-viewmodel
Best practices for implementing Android ViewModels using Kotlin 2.3+ Explicit Backing Fields, StateFlow for UI state, and SharedFlow for one-off events.
- Installs
- 553
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/new-silvermoon/awesome-android-agent-skills --skill android-viewmodel- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads android-viewmodel automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
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.
uiState.value = UiState.Success(data)
2. One-Off Events (SharedFlow)
Purpose
Use for transient events that should not survive recomposition or configuration changes.
Examples:
- Navigate
- Show Snackbar
- Show Toast
- Open Dialog
- Request Permissions
Declaration
val uiEvent: SharedFlow<UiEvent>
field = MutableSharedFlow(
replay = 0,
extraBufferCapacity = 1
)
replay = 0 ensures events are not replayed after recreation.
Using extraBufferCapacity = 1 is recommended for UI events sent with tryEmit().
Sending Events
Suspend:
uiEvent.emit(UiEvent.NavigateBack)
Non-suspending:
uiEvent.tryEmit(UiEvent.ShowSnackbar("Saved"))
3. Collecting in Compose
StateFlow
Always collect lifecycle-aware.
val state by viewModel.uiState.collectAsStateWithLifecycle()
SharedFlow
Collect inside a single LaunchedEffect.
LaunchedEffect(Unit) {
viewModel.uiEvent.collect { event ->
when (event) {
is UiEvent.NavigateBack -> { /* ... */ }
is UiEvent.ShowSnackbar -> { /* ... */ }
}
}
}
Do not collect SharedFlow with collectAsState().
4. Collecting in XML/View System
Use lifecycle-aware collection.
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState.collect {
render(it)
}
}
}
Likewise for events.
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiEvent.collect(::handleEvent)
}
}
5. Coroutine Scope
Launch all ViewModel work in viewModelScope.
viewModelScope.launch {
repository.refresh()
}
Business logic should preferably be delegated to UseCases or Repositories.
6. State Design
Represent the entire screen with a single immutable state object.
data class UiState(
val isLoading: Boolean = false,
val items: List<Item> = emptyList(),
val error: String? = null
)
Avoid exposing multiple unrelated StateFlows for one screen unless they truly have different lifecycles.
7. Best Practices
Expose immutable APIs (StateFlow, SharedFlow)
Prefer Explicit Backing Fields (Kotlin 2.4+)
Use immutable UI state
Use update {} when modifying state
Keep one-off events in SharedFlow
Keep business logic out of Composables
Use collectAsStateWithLifecycle()
Use repeatOnLifecycle() in Views
Launch work in viewModelScope
Do not expose MutableStateFlow
Do not use StateFlow for navigation events
Do not use SharedFlow for persistent screen state
Do not keep duplicate _state properties when Explicit Backing Fields are available
FAQ
What does the android-viewmodel skill do?
Best practices for implementing Android ViewModels using Kotlin 2.3+ Explicit Backing Fields, StateFlow for UI state, and SharedFlow for one-off events.
How do I install android-viewmodel?
Run npx skills add https://github.com/new-silvermoon/awesome-android-agent-skills --skill android-viewmodel in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/android-viewmodel/ (personal) or .claude/skills/android-viewmodel/ (project).
Which AI agents can use android-viewmodel?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is android-viewmodel safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains android-viewmodel?
It is published by new-silvermoon in new-silvermoon/awesome-android-agent-skills. It has 553 recorded installs.
More from new-silvermoon/awesome-android-agent-skills
android-testing
new-silvermoon/awesome-android-agent-skills
Comprehensive testing strategy involving Unit, Integration, Hilt, and Screenshot tests.
gradle-build-performance
new-silvermoon/awesome-android-agent-skills
Debug and optimize Android/Gradle build performance. Use when builds are slow, investigating CI/CD performance, analyzing build scans, or identifying compilation bottlenecks.
compose-ui
new-silvermoon/awesome-android-agent-skills
Best practices for building UI with Jetpack Compose, focusing on state hoisting, detailed performance optimizations, and theming. Use this when writing or refactoring Composable functions.
android-gradle-logic
new-silvermoon/awesome-android-agent-skills
Expert guidance on setting up scalable Gradle build logic using Convention Plugins and Version Catalogs.
android-architecture
new-silvermoon/awesome-android-agent-skills
Expert guidance on setting up and maintaining a modern Android application architecture using Clean Architecture and Hilt. Use this when asked about project structure, module setup, or dependency injection.
kotlin-concurrency-expert
new-silvermoon/awesome-android-agent-skills
Kotlin Coroutines review and remediation for Android. Use when asked to review concurrency usage, fix coroutine-related bugs, improve thread safety, or resolve lifecycle issues in Kotlin/Android code.
Popular mobile skills
design-mobile-apps
designed-by-ai/skills
Design mobile app screens with Sleek, edit Sleek projects, and implement their designs in React Native or HTML.
ios-design
uizze.sh
Design and review iOS UI/UX for iPhone apps in SwiftUI, UIKit, or React Native. Use for mobile app design, screen redesigns, navigation flows, typography, forms, keyboard and safe-area layout, and accessibility checks. Apply Apple Human Interface Guidelines and consult real product references through the optional Uizze connection.
vercel-react-native-skills
vercel-labs/agent-skills
React Native and Expo best practices for building performant mobile apps. Use when building React Native components, optimizing list performance, implementing animations, or working with native modules. Triggers on tasks involving React Native, Expo, mobile performance, or native platform APIs.
animate-expo
emilkowalski/skills
Build animations in React Native and Expo, making the decisions in the order that determines whether they feel right — should it animate, which thread it runs on, which properties, spring or timing, how the gesture hands off, how it degrades. Writes the implementation with Reanimated, Gesture Handler, Expo Router and expo-haptics. Use when animating anything in an Expo app, adding gestures, sheets, screen transitions, press feedback or haptics, or fixing motion that stutters on device. For web animation use animate.
xcode-project-setup
firebase/agent-skills
Safely modifies Xcode projects (.pbxproj) to add Swift Packages and link files. Use this skill whenever an iOS project needs dependencies installed (e.g. Firebase, Alamofire).
firebase-remote-config-basics
firebase/agent-skills
Manages Firebase Remote Config templates, feature flags, loading strategies, and SDKs (Android, iOS). Use when downloading/deploying remoteconfig JSON templates, managing version history/feature flags, setting in-app defaults, fetchAndActivate(), real-time listeners, or SDK setup. Don't use for Firebase Hosting, Auth, Firestore, Data Connect, Crashlytics, or App Hosting.