https://kotlinlang.org logo
#compose
Title
# compose
g

Grigorii Yurkov

10/22/2020, 8:49 PM
I am not sure, is this code effective?
Copy code
@Composable
fun Test() {
    var checked by remember { mutableStateOf(isMyServiceRunning()) }
    if (checked) {
        startMyService()
    } else {
        stopMyService()
    }
    Switch(checked = checked, onCheckedChange = { checked = it})
    // ... A lot of others composable functions
}
As far as I understand, one switch will cause recomposition of entire
Test()
function, won't it?
h

Halil Ozercan

10/22/2020, 10:25 PM
be very careful about how you process state changes. This is one of those things about compose that is going to present a learning curve for the new comers. Many people will incline to introduce a state observer like this without realizing the potential side effects. This composable function might rerun for various reasons. You may add another state in the future without realizing that it will also run the whole function when it mutates. When that happens,
Copy code
if (checked) {
        startMyService()
    } else {
        stopMyService()
    }
this piece of code will be a headache because even though
checked
state doesn't change, function still runs. Instead, I would recommend you to accept a lambda into this composable which can be triggered from
onCheckedChange
.
l

Leland Richardson [G]

10/23/2020, 12:48 AM
When
checked
changes, the
Test
function will recompose. This means it will get reinvoked, but your intuition for how expensive that will be might not be great. In the example you’ve chosen for instance, the
startMyService
stopMyService
and
Switch
calls are all skippable, since their parameters don’t change. As a result, the recomposition of
Test
will be quite efficient
This optimization won’t always be good enough, but it can be pretty effective for most naturally written code
g

Grigorii Yurkov

10/23/2020, 8:57 AM
@Halil Ozercan MyService should rely on
checked
variable and not on switch state. In this example only Switch changes
checked
, but I can add another Composable functions in future.