“Preformance in Jetpack Compose” (性能在Jetpack Compose中)

huangapple go评论55阅读模式
英文:

Preformance in jetpackCompose

问题

I understand your request. Here's the translated code:

正如您在代码中所看到的我有两个可组合函数分别命名为 Screen 和 Body
当 showError 的状态更改时body 函数也会重新组合这会产生任何副作用吗如果是的话如何避免这种重新组合

@Composable
fun Screen(viewModel: ViewModel) {
    val state by viewModel.uiState.collectAsState()
    if (state.showError) {
        Text("示例视图")
    }
    Body(state = state)
}

@Composable
fun Body(state: UiState) {
 // 待办事项
}

Please note that I've translated the code part, as you requested, and didn't include any additional content. If you have any further questions or requests, feel free to ask.

英文:

As you can see in the code, I have two composable functions named Screen and Body.
When the state of the showError changes, the body function is also recompose. Does it have any side effect? If yes, how to avoid this recompose.

    @Composable
    fun Screen(viewModel: ViewModel) {
        val state by viewModel.uiState.collectAsState()
        if (state.showError) {
            Text("sample view")
        }
        Body(state = state)
    }

    @Composable
    fun Body(state: UiState) {
     // todo
    }

答案1

得分: 1

这是compose函数的默认行为。每当观察到状态由于状态值的任何更改而发生变化时,函数会重新组合并显示更新后的值。所以,是的,当使用可组合函数时,有一些事情你可能需要确保,比如,如果你在可组合函数中声明一个变量,然后稍后更新该变量,那么在函数重新组合时,该变量的值将返回到默认状态。

为避免重新组合:我认为在使用状态变量或remember函数时,特别是不太可能实现,但你可以尽量减少所需的重新组合次数。

以下是有关其生命周期如何运作的参考链接:

https://developer.android.com/jetpack/compose/lifecycle

英文:

This is the default behaviour of the compose function. Whenever a state is observed due to any change in state value, the function recomposes and displays the updated values. So, yeah there are things that you may need to make sure when using the composable functions like for example, if you are declaring a variable in a composable function and that variable is later updated then that variable's value will go in default state when function is recomposed.

To avoid recomposition: I do not think that is possible specially when you are using state variables or remember functions but what you can do is minimise the recompositions needed.

Below is a reference on how its lifecycle works.

https://developer.android.com/jetpack/compose/lifecycle

huangapple
  • 本文由 发表于 2023年3月31日 04:17:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定