Compose 状态管理模式实践:Unidirectional Data Flow 解析
状态管理架构模式最佳实践
Compose 的声明式特性要求我们重新审视数据流向。无论是采用 ViewModel+StateFlow,还是使用 Orbit、Mavericks 等框架,核心目标都是将状态变化限制在可预期的范围内。
三种常见模式对比
- ViewModel + StateFlow:官方推荐方案,适合大多数中型项目;
- Unidirectional Data Flow (UDF):强调输入输出的单向性,易于配合测试快照;
- Redux/MVI:事件驱动,适合复杂交互或需要时光旅行调试的场景。
Note: 务必避免在 Composable 内部直接持有可变状态,否则会增大重组不一致风险。
示例:过滤器面板
以下代码展示了如何在 ViewModel 中集中处理意图,再把结果通过不可变 State 推送给UI层:
@Stable
data class FilterState(
val categories: List<String> = emptyList(),
val selected: Set<String> = emptySet()
)
sealed interface FilterIntent {
data class Toggle(val category: String) : FilterIntent
data object Reset : FilterIntent
}
class FilterViewModel : ViewModel() {
private val _state = MutableStateFlow(FilterState())
val state: StateFlow<FilterState> = _state.asStateFlow()
fun dispatch(intent: FilterIntent) {
_state.update { current ->
when (intent) {
is FilterIntent.Toggle -> current.copy(
selected = current.selected.toggle(intent.category)
)
FilterIntent.Reset -> current.copy(selected = emptySet())
}
}
}
}