KotlinLeaner
02/01/2023, 3:19 PMviewmodel
with LaunchEffect
. If there is any problem or better way please guide me on this. Thanks@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")
}
}
Composable
function.Lilly
02/01/2023, 3:38 PMbackgroundColor
except simply changing its valueKotlinLeaner
02/01/2023, 3:39 PMLilly
02/01/2023, 3:41 PMmutableStateOf
KotlinLeaner
02/01/2023, 3:42 PMLilly
02/01/2023, 3:43 PMbackgroundColor
outside of Compose scopeKotlinLeaner
02/01/2023, 3:45 PMbackgroundColor
outside of compose. I used viewmodel because It can be used for unit testing. Composable functions are not testable.Lilly
02/01/2023, 3:50 PMKotlinLeaner
02/01/2023, 3:56 PM