Skip to content

Instantly share code, notes, and snippets.

@damianpetla
Last active August 28, 2021 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damianpetla/7367d13a9b380a01dd4951de055458d3 to your computer and use it in GitHub Desktop.
Save damianpetla/7367d13a9b380a01dd4951de055458d3 to your computer and use it in GitHub Desktop.
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