Search code examples
kotlinandroid-jetpack-composecompose-recompositionjetpack-compose-animation

Continuous recomposition in Jetpack Compose


I'm trying to create a sky view in my Android app using Jetpack Compose. I want to display it inside a Card with a fixed height. During nigth time, the card background turns dark blue and I'd like to have some blinking stars spread over the sky.

To create the stars blinking animation, I'm using an InfiniteTransition object and a scale property with animateFloat that I apply to several Icons. Those Icons are created inside a BoxWithConstraints, to spread then randomly using a for loop. The full code I'm using is shown below:

@Composable
fun NightSkyCard() {
    Card(
        modifier = Modifier
            .height(200.dp)
            .fillMaxWidth(),
        elevation = 2.dp,
        shape = RoundedCornerShape(20.dp),
        backgroundColor = DarkBlue
    ) {
        val infiniteTransition = rememberInfiniteTransition()
        val scale by infiniteTransition.animateFloat(
            initialValue = 1f,
            targetValue = 0f,
            animationSpec = infiniteRepeatable(
                animation = tween(1000),
                repeatMode = RepeatMode.Reverse
            )
        )
        
        BoxWithConstraints(
            modifier = Modifier.fillMaxSize()
        ) {
            for (n in 0..20) {
                val size = Random.nextInt(3, 5)
                val start = Random.nextInt(0, maxWidth.value.toInt())
                val top = Random.nextInt(10, maxHeight.value.toInt())
                
                Icon(
                    imageVector = Icons.Filled.Circle,
                    contentDescription = null,
                    modifier = Modifier
                        .padding(start = start.dp, top = top.dp)
                        .size(size.dp)
                        .scale(scale),
                    tint = Color.White
                )
            }
            
        }
    }
}

The problem with this code is that the BoxWithConstraints's scope is recomposing continously, so I get a lot of dots appearing and dissapearing from the screen very fast. I'd like the scope to just run once, so that the dots created at first time would blink using the scale property animation. How could I achieve that?


Solution

  • Instead of continuous recomposition you should look for least amount of recompositions to achieve your goal.

    Compose has 3 phases. Composition, Layout and Draw, explained in official document. When you use a lambda you defer state read from composition to layout or draw phase.

    If you use Modifier.scale() or Modifier.offset() both of three phases above are called. If you use Modifier.graphicsLayer{scale} or Modifier.offset{} you defer state read to layout phase. And the best part, if you use Canvas, which is a Spacer with Modifier.drawBehind{} under the hood, you defer state read to draw phase as in example below and you achieve your goal only with 1 composition instead of recomposing on every frame.

    For instance from official document

    // Here, assume animateColorBetween() is a function that swaps between
    // two colors
    val color by animateColorBetween(Color.Cyan, Color.Magenta)
    
    Box(Modifier.fillMaxSize().background(color))
    

    Here the box's background color is switching rapidly between two colors. This state is thus changing very frequently. The composable then reads this state in the background modifier. As a result, the box has to recompose on every frame, since the color is changing on every frame.

    To improve this, we can use a lambda-based modifier–in this case, drawBehind. That means the color state is only read during the draw phase. As a result, Compose can skip the composition and layout phases entirely–when the color changes, Compose goes straight to the draw phase.

    val color by animateColorBetween(Color.Cyan, Color.Magenta)
    Box(
       Modifier
          .fillMaxSize()
          .drawBehind {
             drawRect(color)
          }
    )
    

    And how you can achieve your result

    @Composable
    fun NightSkyCard2() {
        Card(
            modifier = Modifier
                .height(200.dp)
                .fillMaxWidth(),
            elevation = 2.dp,
            shape = RoundedCornerShape(20.dp),
            backgroundColor = Color.Blue
        ) {
            val infiniteTransition = rememberInfiniteTransition()
            val scale by infiniteTransition.animateFloat(
                initialValue = 1f,
                targetValue = 0f,
                animationSpec = infiniteRepeatable(
                    animation = tween(1000),
                    repeatMode = RepeatMode.Reverse
                )
            )
    
            val stars = remember { mutableStateListOf<Star>() }
    
    
            BoxWithConstraints(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Blue)
            ) {
    
                SideEffect {
                    println("🔥 Recomposing")
                }
                
                LaunchedEffect(key1 = Unit) {
                    repeat(20) {
                        stars.add(
                            Star(
                                Random.nextInt(2, 5).toFloat(),
                                Random.nextInt(0, constraints.maxWidth).toFloat(),
                                Random.nextInt(10, constraints.maxHeight).toFloat()
                            )
                        )
                    }
                }
                
                Canvas(modifier = Modifier.fillMaxSize()) {
                   if(stars.size == 20){
                       stars.forEach { star ->
                           drawCircle(
                               Color.White,
                               center = Offset(star.xPos, star.yPos),
                               radius = star.radius *(scale)
                           )
                       }
                   }
                }
            }
        }
    }
    
    @Immutable
    data class Star(val radius: Float, val xPos: Float, val yPos: Float)