You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

预览Composable时如何测试MutableStateFlow?

问题根源

每次Composable重组时,你在PreviewFoo里创建的MutableStateFlow都会被重新实例化,导致输入更新触发重组后,新的StateFlow又回到初始值。而ViewModel的实例是跨重组持久化的,所以不会出现这个问题。

修复代码

用remember持有MutableStateFlow实例,确保它在重组时不会被重新创建:

@Preview
@Composable
fun PreviewFoo() {
    // 用remember保留StateFlow实例,避免重组时重新初始化
    val itemDescriptionMutableStateFlow = remember { MutableStateFlow("SomeInitValue") }
    val itemDescription by itemDescriptionMutableStateFlow.collectAsState()

    Foo(
        itemDescription = itemDescription,
        setItemDescription = { newDesc ->
            itemDescriptionMutableStateFlow.value = newDesc
        }
    )
}
额外说明
  • remember会在Composable的生命周期内维持对象实例,仅当Composable被销毁时才释放,完全满足预览场景的状态持久需求。
  • 若需要在配置变更(如横竖屏切换)时也保留状态,可替换为rememberSaveable,但预览场景下remember已足够。

内容的提问来源于stack exchange,提问作者J. Cool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 04:09:56