Home > OS >  How to Improve performance with Jetpack Compose (when assembling something inside a @Composable func
How to Improve performance with Jetpack Compose (when assembling something inside a @Composable func

Time:05-25

Suppose I have two composables in my app:

@Composable
fun CoreKeyboard(keyboardKeys: List<List<KeyboardKey>>, ...) {
    // ...
}

and

@Composable
fun NumberKeyboard(...) {
    val keyboardKeys = listOf(
        listOf(KeyboardKey("1"), KeyboardKey("2"), KeyboardKey("3")),
        listOf(KeyboardKey("4"), KeyboardKey("5"), KeyboardKey("6")),
        listOf(KeyboardKey("7"), KeyboardKey("8"), KeyboardKey("9")),
        listOf(KeyboardKey("0"))
    )

    CoreKeyboard(keyboardKeys = keyboardKeys, ...)

}

If I'm not wrong, this approach is not very performatic as in every recomposition the keyboardKeys in NumberKeyboard will be reassembled.

What is the best way to do this?

I thought about using by remember { mutableStateOf(...) }, but keyboardKeys is immutable. Is it still a good approach?

CodePudding user response:

If you have something that is expensive to compute and you want to compute it on your composable only once, simply wrap it with remember

val keyboardKeys = remember {
    listOf(
    listOf(KeyboardKey("1"), KeyboardKey("2"), KeyboardKey("3")),
    listOf(KeyboardKey("4"), KeyboardKey("5"), KeyboardKey("6")),
    listOf(KeyboardKey("7"), KeyboardKey("8"), KeyboardKey("9")),
    listOf(KeyboardKey("0"))
    )
}

You only need the mutableStateOf if you want to mutate the value so that it can be observed.

  • Related