预览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
相关产品推荐
相关产品推荐

