[Jetpack Compose] 1. Compose 기본 사항(3) #States #ViewModel
📌참고자료
State in Jetpack Compose
📌참고자료
- Stateful composable: composable that owns state
- Stateless composable: composable that doesn't hold any state
- State hoisting:
- pattern of moving state to a composable's caller to make composable stateless
- Compose에서 UDF를 구현하는 방법
- Unidirectional Data Flow(UDF):
a pattern where state goes down & events go up
- State hoisting의 장점
- single source of truth -> avoid bugs
- state can be shared with multiple composables
- intercepted by callers -> callers can decide whether to ignore or modify state
- state is decoupled from composable
@Composable
fun StatefulCounter(modifier: Modifier = Modifier) {
var count by rememberSaveable { mutableStateOf(0) }
StatelessCounter(count, { count++ }, modifier)
}
@Composable
fun StatelessCounter(count: Int, onIncrement: () -> Unit, modifier: Modifier = Modifier) {
Column(modifier = modifier.padding(16.dp)) {
if (count > 0) {
Text("You've had $count glasses.")
}
Button(onClick = onIncrement, Modifier.padding(top = 8.dp), enabled = count < 10) {
Text("Add one")
}
}
}
- ViewModels live longer than the composition
import androidx.lifecycle.viewmodel.compose.viewModel
@Composable
fun WellnessScreen(
modifier: Modifier = Modifier,
wellnessViewModel: WellnessViewModel = viewModel()
) {
Column(modifier = modifier) {
StatefulCounter()
WellnessTasksList(
list = wellnessViewModel.tasks,
onCloseTask = { task -> wellnessViewModel.remove(task) })
}
}