【发布时间】:2021-11-03 09:13:25
【问题描述】:
我真的很喜欢将by 委托与Compose State 一起使用,因为它隐藏了具有“反应性”数据的样板,即:
val message: String by remember { mutableStateOf("") }
message = "No boilerplate"
以这种方式使用 props 时,单向数据流(或 props down,event up)是干净且容易的。
但是,当想要在 data class 中将数据组合在一起,或将视图模型道具作为状态观察(即:使用 observeAsAState())时,我必须声明 State 类型的道具,例如:
data class MyUiProps(
val message: State<String>
)
/*
* Different ways of creating instances of `MyUiProps`.
*
* In the examples the result is of type `State` rather than
* `String` like using the `by` delegate
*
*/
var props = MyUiProps(viewModel.message.observesAsState(""))
props = MyUiProps(remember { mutableStateOf("") })
props.message.value = "Urgh boilerplate"
有没有办法将by 委托与如下伪代码类似的数据类一起使用
data class MyUiProps(
val message: String
)
val props = MyUiProps(
message = by remember { mutableStateOf("") }
)
props.message = "Yay no boilerplate"
【问题讨论】:
标签: android kotlin android-jetpack-compose android-jetpack