https://kotlinlang.org logo
#compose
Title
# compose
k

KotlinLeaner

02/01/2023, 3:19 PM
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

Lilly

02/01/2023, 3:38 PM
Your approach makes only sense if you want to do something else with
backgroundColor
except simply changing its value
k

KotlinLeaner

02/01/2023, 3:39 PM
yes i'll change with different colors with specfic number
l

Lilly

02/01/2023, 3:41 PM
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

KotlinLeaner

02/01/2023, 3:42 PM
How can I set the background color? Sorry I didn't get it. Can you please provide me example?
l

Lilly

02/01/2023, 3:43 PM
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

KotlinLeaner

02/01/2023, 3:45 PM
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

Lilly

02/01/2023, 3:50 PM
If you just want to demonstrate how to extract business logic, then it's done properly
k

KotlinLeaner

02/01/2023, 3:56 PM
Thank you for your guidance. It clears my doubts.
6 Views