我有一个可组合项,我想用可变状态流模拟不断变化的输入。简而言之,我有一个可组合项,您可以在其中传递一个名为项目描述的字符串字段,该可组合项会显示该字段。如果用户输入新的描述,则 mutablestateflow 应更新为新输入的描述。 我试图在开发时测试我的组件,而无需为其编写完整的视图模型。
这是我的可组合项:
@Composable
fun Foo(itemDescription: String, setItemDescription: (newDescription: String) -> Unit) {
OutlinedTextField(value = itemDescription, onChange = { it -> setItemDescription(it) })
}
这就是我尝试预览它的方式:
@Preview
@Composable
fun PreviewFoo() {
val itemDescriptionMutableStateFlow = MutableStateFlow("SomeInitValue")
val itemDescriptionStateFlow = itemDescriptionStateFlow.asStateFlow()
val itemDescription by itemDescriptionStateFlow.collectAsState()
val itemDescription by itemDescription
Foo(itemDescription = itemDescription, setItemDescription = {
itemDescriptionMutableStateFlow.value = it
})
}
但是如果我这样做,无论我在概述的文本字段中输入什么值,它都会继续显示“SomeInitValue”,这是可变状态流的初始值。如果我使用视图模型来存储可变状态流而不是直接使用可变状态流,则此设置有效。
如何在测试组件时模拟可变状态流?或者我在这里做错了什么?任何帮助都会很棒!
似乎正在发生的情况是,预览功能会随着每个字符的输入而重新组合。这导致
itemDescriptionMutableStateFlow
每次都重新初始化并重置预览中文本字段的值。您需要记住 MutableStateFlow
才能避免这种情况。
@Preview
@Composable
fun PreviewFoo() {
val itemDescriptionMutableStateFlow = remember {
MutableStateFlow("SomeInitValue")
}
val text by itemDescriptionMutableStateFlow.collectAsState()
Foo(itemDescription = text, setItemDescription = {
itemDescriptionMutableStateFlow.value = it
})
}
在这种特殊情况下,您还可以使用
MutableState
进行预览/测试。
@Preview
@Composable
fun PreviewFoo() {
var text by remember { mutableStateOf("SomeInitValue") }
Foo(itemDescription = text, setItemDescription = {
text = it
})
}