Home > Software design >  Continuous recomposition in Jetpack Compose
Continuous recomposition in Jetpack Compose

Time:08-08

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?

CodePudding user response:

One solution is to wrap your code in a LaunchedEffect so that the animation runs once:

@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) {
                var size by remember { mutableStateOf(0) }
                var start by remember { mutableStateOf(0) }
                var top by remember { mutableStateOf(0) }
                
                LaunchedEffect(key1 = Unit) {    
                    size = Random.nextInt(3, 5)
                    start = Random.nextInt(0, maxWidth.value.toInt())
                    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
                )
            }
        }
    }
}

You then get 21 blinking stars.

CodePudding user response:

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

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

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 you achieve your goal only with 1 composition instead of recomposing 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("           
  • Related