Agent Skills
› maxrave-dev/SimpMusic
› android-viewmodel
android-viewmodel
GitHub提供Android ViewModel最佳实践,指导使用StateFlow管理UI状态,SharedFlow处理一次性事件。涵盖初始化、线程安全更新及Compose/XML中的收集方式,确保配置变更存活。
Trigger Scenarios
实现Android ViewModel
处理UI状态管理
配置StateFlow或SharedFlow
Install
npx skills add maxrave-dev/SimpMusic --skill android-viewmodel -g -y
SKILL.md
Frontmatter
{
"name": "android-viewmodel",
"description": "Best practices for implementing Android ViewModels, specifically focused on StateFlow for UI state and SharedFlow for one-off events."
}
Android ViewModel & State Management
Instructions
Use ViewModel to hold state and business logic. It must outlive configuration changes.
1. UI State (StateFlow)
- What: Represents the persistent state of the UI (e.g.,
Loading,Success(data),Error). - Type:
StateFlow<UiState>. - Initialization: Must have an initial value.
- Exposure: Expose as a read-only
StateFlowbacking a privateMutableStateFlow.private val _uiState = MutableStateFlow<UiState>(UiState.Loading) val uiState: StateFlow<UiState> = _uiState.asStateFlow() - Updates: Update state using
.update { oldState -> ... }for thread safety.
2. One-Off Events (SharedFlow)
- What: Transient events like "Show Toast", "Navigate to Screen", "Show Snackbar".
- Type:
SharedFlow<UiEvent>. - Configuration: Must use
replay = 0to prevent events from re-triggering on screen rotation.private val _uiEvent = MutableSharedFlow<UiEvent>(replay = 0) val uiEvent: SharedFlow<UiEvent> = _uiEvent.asSharedFlow() - Sending: Use
.emit(event)(suspend) or.tryEmit(event).
3. Collecting in UI
- Compose: Use
collectAsStateWithLifecycle()forStateFlow.
Forval state by viewModel.uiState.collectAsStateWithLifecycle()SharedFlow, useLaunchedEffectwithLocalLifecycleOwner. - Views (XML): Use
repeatOnLifecycle(Lifecycle.State.STARTED)within a coroutine.
4. Scope
- Use
viewModelScopefor all coroutines started by the ViewModel. - Ideally, specific operations should be delegated to UseCases or Repositories.
Version History
- 11f5926 Current 2026-07-30 20:16


