I have a composable that is responsible to return ...
# compose
m
I have a composable that is responsible to return a color in sequence from an array each time called. To make it work in sequence and remember what it returned last time, I added remember{mutableStateOf()}. I am using this composable to draw a group of boxes in another composable. The problem is the colors start to flicker in a scary way! Any idea why this happens?
Copy code
@Composable
fun pickColor(): Color {
    val colors = listOf(
        Color.Black,
        Color.Gray,
        Color.Magenta,
        Color.Yellow,
        Color.LightGray,
        Color.Cyan,
        Color.Blue,
        Color.DarkGray
    )

//    val index = Random.nextInt(0,colors.count() - 1)
    var index by remember{mutableStateOf(0)}

    return if (index < colors.count()) {val temp = colors[index]; index++; temp}
    else {index=0;colors[index]}
}
The code that calls pickColor:
Copy code
var count = remember{mutableStateOf(0)}
val size = 400.dp
    Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize()) {
        Box(modifier = Modifier.size(size).background(Color.Red), contentAlignment = Alignment.Center){
            var childSize = size - 20.dp
            for (i in 0 until count.value){
                Box(modifier = Modifier.size(childSize).background(pickColor()))
                childSize -= 20.dp
            }
        }
        OutlinedTextField(value = "${count.value}", onValueChange = {})
        Row {
            Button(onClick = { count.value++ }, modifier= Modifier.padding(8.dp)) {
                Row{
                    Icon(imageVector = Icons.Rounded.Add, contentDescription = "Increase")
                    Text("Increase")
                }
            }
            Button(onClick = { count.value = if (count.value <= 0) 0 else count.value-1 }, Modifier.padding(8.dp)) {
                Row{
                    Icon(painter = painterResource(id = R.drawable.ic_baseline_remove_24), contentDescription = "Delete")
                    Text("Decrease")
                }


            }
        }

    }
z
You’re incrementing your mutable state every composition, but also reading it in the same composition, so when the mutation invalidates the scope, that causes another composition, which causes another invalidation, etc
You need a more stable event to trigger the increment
m
Do you think hoisting count will help?
z
It could, although you could hoist the count and still make the same mistake (a composable that has a non unit return value doesn’t delineate a recompose scope). But I’m guessing your caller is in a much better position to decide when to increment
1