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

Rick Regan

02/16/2021, 5:47 PM
I'm trying to reconcile the single source of truth/state hoisting principle with the discrete
Slider
. As far as I can tell, it's not possible to hoist the discrete slider state and have it control the slider, meaning the local continuous slider state is the actual source of truth (see code in thread -- you of course can't reset the slider from the callback). You need to maintain continuous slider state so that the slider moves smoothly -- instead of jumping -- between discrete values. Obviously I could fix this by hoisting the continuous state, but then the slider is no longer conceptually discrete at that level; I'd have to move the "discreteness processing" up there. I don't think there's anything to be done about it; I guess I'm just saying that the discrete slider abstraction is "leaky".
Copy code
var hoistedDiscreteSliderValue by remember { mutableStateOf(0) }
SliderTruth(
    hoistedDiscreteSliderValue,
    { hoistedDiscreteSliderValue = it },
    { hoistedDiscreteSliderValue = 0 }
)

@Composable
fun SliderTruth(
    discreteSliderValue: Int,
    onDiscreteSliderValueChange: (newDiscreteSliderValue: Int) -> Unit,
    onSliderReset: () -> Unit
) {
    var continuousSliderValue by remember { mutableStateOf(discreteSliderValue.toFloat()) }
    Column {
        Slider(
            valueRange = 0f..20f,
            steps = 3, // Step size of 5
            value = continuousSliderValue,
            onValueChange = {
                continuousSliderValue = it
                val newDiscreteSliderValue = (continuousSliderValue).toInt()
                if (newDiscreteSliderValue in 0..20 step 5)
                    onDiscreteSliderValueChange(newDiscreteSliderValue)
            },
        )
        Button(onClick = { onSliderReset() }
        ) {
            Text(text = "Reset slider")
        }
    }
}
m

matvei

02/16/2021, 5:52 PM
I think you are right. Be design decision initially we made the discrete slider is just a continuous slider that has a guarantee to be stopped only at the particular stops... The only way to share same source of truth is to move "discreteness processing" up unfortunately. That being said, I think it's worth filing a bug so we can reconsider it later on
r

Rick Regan

02/16/2021, 5:54 PM
I can do that, though I can't envision a solution. (I don't suppose you have one in mind?)
m

matvei

02/16/2021, 5:58 PM
Other than to have a separate DescreteSlider with different API shape -- no 🙂
r

Rick Regan

02/16/2021, 6:05 PM
Or perhaps moving what I am doing around the Slider into the Slider, so that the slider moves continuously and only calls back on discrete values when
steps
is specified? That would not change the API I don't think.
(It would break how people use the API, if that's a valid distinction.)
m

matvei

02/17/2021, 11:37 AM
Thanks!