Hey guys, I am working on changing background colo...
# compose
k
Hey guys, I am working on changing background color of button. I want to know my example is good to use simple business logic in
viewmodel
with
LaunchEffect
. If there is any problem or better way please guide me on this. Thanks
Copy code
@Composable
fun ItemColorStateful() {
    var index by remember { mutableStateOf(-1) }
    val vm = koinViewModel<ColorViewModel>()
    LaunchedEffect(key1 = index) {
        vm.changeBackgroundColor(index)
    }
    Column(modifier = Modifier.fillMaxSize()) {
        Text(text = "Different Color")
        ButtonScopeStateless(
            index = index,
            onIndexChange = {
                index = it
            },
            backgroundColor = vm.backgroundColor
        )
    }
}

class ColorViewModel : BaseViewModel() {
    var backgroundColor by mutableStateOf(Color.Blue)

    fun changeBackgroundColor(index: Int) {
        backgroundColor = if (index != -1) {
            Color.Gray
        } else {
            Color.Blue
        }
    }
}

@Composable
fun ButtonScopeStateless(
    index: Int,
    onIndexChange: (Int) -> Unit,
    backgroundColor: Color,
) {
    Button(
        colors = ButtonDefaults.buttonColors(backgroundColor = backgroundColor),
        onClick = { onIndexChange(index + 1) }
    ) {
        Text(text = "Click Me $index")
    }
}
My main goal is to avoid business logic in
Composable
function.
l
Your approach makes only sense if you want to do something else with
backgroundColor
except simply changing its value
k
yes i'll change with different colors with specfic number
l
If you dont need backgroundColor outside of Compose, you can set value of index directly and Compose will automatically recompose the related components since you have defined you index as
mutableStateOf
k
How can I set the background color? Sorry I didn't get it. Can you please provide me example?
l
What you are doing is correct, but you dont have to involve a viewmodel if you don't need
backgroundColor
outside of Compose scope
k
Yes I don't need
backgroundColor
outside of compose. I used viewmodel because It can be used for unit testing. Composable functions are not testable.
In my mentor project, testing is mandatory. I cannot find code coverage for composable stuffs. So that's why I moved to all business logic to viewmodel
l
If you just want to demonstrate how to extract business logic, then it's done properly
k
Thank you for your guidance. It clears my doubts.