0

There is a simple piece of code, One button plus three components with random background colors. when I press the button, Two composables that used DrawScope are redrawn again (I think it is due to the ripple effect of the button).

enter image description here

Is it a recomposition!? The Document says :

Recomposition is the process of calling your composable functions again when inputs change. This happens when the function's inputs change. When Compose recomposes based on new inputs, it only calls the functions or lambdas that might have changed, and skips the rest.

How can I prevent this?

private fun randomColor() = Color(
    Random.nextInt(256),
    Random.nextInt(256),
    Random.nextInt(256),
    alpha = 255
)


@Preview
@Composable
fun preview() {
    Column {

        Button(onClick = { /*nothing*/ }) { Text(text = "Do nothing") }

        Canvas(modifier = Modifier
            .fillMaxWidth().height(100.dp) ){
            drawCircle(color = randomColor(), radius = size.minDimension*.4f)
        }

        Text(modifier = Modifier
            .drawBehind {
                drawRect(color = randomColor())
            }.fillMaxWidth().height(50.dp),
            text="Text component with drawBehind")

        Text(modifier = Modifier
            .background(color = randomColor())
            .fillMaxWidth()
            .height(50.dp),text="Background color set on the modifier")
    }
}
ucMedia
  • 4,105
  • 4
  • 38
  • 46
  • 1
    First of all that's not recomposition. `Modifier.drawBehind` and `Canvas` which is a `Spacer` with `Modifier.drawBehind` calls draw phase only. You can verify this using a `SideEffect` inside `preview ` or `Column`. Also testing your code i don't see any draw calls, no color change, with Jetpack compose version 1.5.0-beta03. This might be a bug in previous versions because recomposition was causing another non related Composables to call draw phase or `Canvas` drawing – Thracian Sep 02 '23 at 10:26
  • 1
    Here is the question i mentioned. https://stackoverflow.com/questions/73298018/unable-to-stop-the-canvas-composables-draw-scope-from-triggering-continuously?noredirect=1&lq=1 – Thracian Sep 02 '23 at 10:27
  • 1
    @Thracian Thank you so much update to 1.6.0-alpha03, And now everything works fine. thanks again – ucMedia Sep 02 '23 at 10:46
  • 1
    You are welcome. When you use Modifiers with lambda you are not scheduling recomposition you either call Layout phase or Draw phase skipping recomposition. You can also check out my question about which phases are called in which modifier usages. https://stackoverflow.com/questions/72457805/jetpack-compose-deferring-reads-in-phases-for-performance. And official document is here https://developer.android.com/jetpack/compose/phases – Thracian Sep 02 '23 at 10:50

0 Answers0