[英]Could you give me some sample code to prove Never depend on side-effects from executing composable functions?
The following content is from the article .以下内容来自文章。
Never depend on side-effects from executing composable functions, since a function's recomposition may be skipped.永远不要依赖于执行可组合函数的副作用,因为函数的重组可能会被跳过。 If you do, users may experience strange and unpredictable behavior in your app.如果您这样做,用户可能会在您的应用中遇到奇怪且不可预测的行为。 A side-effect is any change that is visible to the rest of your app.副作用是对您的应用程序的其余部分可见的任何更改。 For example, these actions are all dangerous side-effects:例如,这些动作都是危险的副作用:
Writing to a property of a shared object
Updating an observable in ViewModel
Updating shared preferences
It says that there are three case to cause recomposition be skipped, but it doesn't give me sample code.它说有三种情况会导致跳过重组,但它没有给我示例代码。
Epecially, I convert a LiveData
which is observable to State<T>
for Compose, the UI will be updated automatically when the value of the LiveData
is updated!特别是,我将可观察到的LiveData
转换为用于 Compose 的State<T>
,当LiveData
的值更新时,UI 将自动更新!
Could you give me some sample code to prove Never depend on side-effects from executing composable functions ?你能给我一些示例代码来证明从不依赖执行可组合函数的副作用吗?
I do not know Jetpack, but I presume the idea is that UI refresh will only be triggered by a State
change.我不知道 Jetpack,但我认为这个想法是 UI 刷新只会由State
更改触发。 In other words, only Composable
functions that depend on a State
will update.换句话说,只有依赖于State
Composable
函数才会更新。
Okay (better would be if we extracted the state and the callback, but just for the example) :好的(如果我们提取状态和回调会更好,但仅用于示例) :
@Composable
fun Example() {
var counter by remember { mutableStateOf(0) }
Row {
Text(counter.toString())
Checkbox(checked = value, onCheckedChange = { counter++ })
}
}
Bad Side-Effects:不良副作用:
object GlobalCounterState {
var counter = 0
}
@Composable
fun Example() {
Row {
Text(GlobalCounterState.counter.toString())
Checkbox(checked = value, onCheckedChange = { GlobalCounterState.counter++ })
}
}
Side-effects is anything that leaves the function scope.副作用是任何离开函数作用域的东西。 For example, external mutations (such as in the example above) or UI changes (such as calling a Toast/Snackbar) or clearing a disposable/subscription.例如,外部突变(如上例中)或 UI 更改(如调用 Toast/Snackbar)或清除一次性/订阅。 In JetPack Composable
functions can re-run at any time and any number of times.在 JetPack Composable
函数可以随时重新运行任意次数。 It needs to be pure and deterministic.它需要是纯粹的和确定性的。 Meaning, given the same input, the effect or result must be identical regardless if called 10 or 1000 times.意思是,给定相同的输入,无论调用 10 次还是 1000 次,效果或结果都必须相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.