Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class MainActivity : ComponentActivity() {
private val viewModel by viewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeStateTestTheme {
val state: MainState by viewModel.state.collectAsState()
MainScaffold(
state,
onValueUpdate = { viewModel.updateSlider(it.roundToInt()) },
onButtonClick = { viewModel.updateCounter() }
)
}
}
}
}
@Composable
fun MainScaffold(state: MainState, onValueUpdate: (Float) -> Unit, onButtonClick: () -> Unit) {
Scaffold(modifier = Modifier.fillMaxSize()) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
.verticalScroll(rememberScrollState())
) {
Slider(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp),
value = state.sliderValue.toFloat(),
onValueChange = onValueUpdate,
valueRange = 0f..10f,
steps = 10
)
CounterRow(counter = state.counter, onButtonClick = onButtonClick)
}
}
}
@Composable
fun CounterRow(counter: Int, onButtonClick: () -> Unit) {
/** SHOULD NOT BE CALLED ON SLIDER CHANGE **/
Row(modifier = Modifier.fillMaxWidth()) {
Button(onClick = onButtonClick) {
Text(text = "Click me!")
}
Spacer(modifier = Modifier.width(24.dp))
Text(text = counter.toString())
}
}
data class MainState(
val sliderValue: Int = 0,
val counter: Int = 0
)
class MainViewModel : ViewModel() {
private val _state = MutableStateFlow(MainState())
val state: StateFlow<MainState>
get() = _state.asStateFlow()
fun updateCounter() {
_state.value = state.value.copy(counter = state.value.counter.plus(1))
}
fun updateSlider(value: Int) {
_state.value = state.value.copy(sliderValue = value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment