android-viewmodel by new-silvermoon/awesome-android-agent-skills
npx skills add https://github.com/new-silvermoon/awesome-android-agent-skills --skill android-viewmodel使用 ViewModel 来持有状态和业务逻辑。它必须在配置变更后依然存在。
定义 : 代表 UI 的持久化状态(例如,Loading、Success(data)、Error)。
类型 : StateFlow<UiState>。
初始化 : 必须有一个初始值。
对外暴露 : 对外暴露为只读的 StateFlow,背后是一个私有的 MutableStateFlow。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
private val _uiState = MutableStateFlow<UiState>(UiState.Loading)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
更新 : 使用 .update { oldState -> ... } 来更新状态以确保线程安全。
定义 : 瞬态事件,例如"显示 Toast"、"导航到屏幕"、"显示 Snackbar"。
类型 : SharedFlow<UiEvent>。
配置 : 必须使用 replay = 0 来防止事件在屏幕旋转时重新触发。
private val _uiEvent = MutableSharedFlow<UiEvent>(replay = 0)
val uiEvent: SharedFlow<UiEvent> = _uiEvent.asSharedFlow()
发送 : 使用 .emit(event)(挂起函数)或 .tryEmit(event)。
Compose : 对于 StateFlow,使用 collectAsStateWithLifecycle()。
val state by viewModel.uiState.collectAsStateWithLifecycle()
对于 SharedFlow,在 LaunchedEffect 中使用 LocalLifecycleOwner。
repeatOnLifecycle(Lifecycle.State.STARTED)。viewModelScope。每周安装量
156
代码仓库
GitHub 星标数
552
首次出现
2026年1月27日
安全审计
安装于
codex137
opencode137
gemini-cli126
github-copilot122
kimi-cli112
amp111
Use ViewModel to hold state and business logic. It must outlive configuration changes.
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 StateFlow backing a private MutableStateFlow.
private val _uiState = MutableStateFlow<UiState>(UiState.Loading)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
Updates : Update state using .update { oldState -> ... } for thread safety.
What : Transient events like "Show Toast", "Navigate to Screen", "Show Snackbar".
Type : SharedFlow<UiEvent>.
Configuration : Must use replay = 0 to 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).
Compose : Use collectAsStateWithLifecycle() for StateFlow.
val state by viewModel.uiState.collectAsStateWithLifecycle()
For SharedFlow, use LaunchedEffect with LocalLifecycleOwner.
repeatOnLifecycle(Lifecycle.State.STARTED) within a coroutine.viewModelScope for all coroutines started by the ViewModel.Weekly Installs
156
Repository
GitHub Stars
552
First Seen
Jan 27, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex137
opencode137
gemini-cli126
github-copilot122
kimi-cli112
amp111
Kotlin Exposed ORM 模式指南:DSL查询、DAO、事务管理与生产配置
983 周安装