用途:为 Android 应用配置 ViewModel 的状态发布方式,规范状态建模与共享策略。
主要能力:
- 结构 ViewModel:通过 .asStateFlow() 暴露唯一的 StateFlow<UiState>;所有协程使用 viewModelScope;在 init 块触发初始加载。
- 定义 UI 状态(LCE 模式):使用 sealed interface,包含 Loading、Content、Error 变体;数据类标注 @Immutable。
- 生命周期安全收集:Compose 中使用 collectAsStateWithLifecycle();共享资源使用 SharingStarted.WhileSubscribed(5000)。
反模式:新代码不用 LiveData,改用 StateFlow;不公开 MutableStateFlow,只暴露 .asStateFlow();ViewModel 中不持有 Context,避免泄漏 Activity,确需时用 Application context。
验证:每个 ViewModel 恰好暴露一个 StateFlow<UiState>;UiState 为含 Loading、Content、Error 的密封接口;UI 用 collectAsStateWithLifecycle() 收集;ViewModel 测试通过 ./gradlew test。
限制:资料未提供具体模板代码、依赖版本、安装命令及适用 Android/Compose 版本,暂未提供。