https://kotlinlang.org logo
Title
t

trashcoder

04/07/2022, 8:57 PM
Hi, I ran into a problem with setting a `Slider`'s state/position. I use `Slider`s to control the brightness of lights and the level of shutters. I store the
Slider
position in a variable like this:
var shutterLevel by remember { mutableStateOf(shutter.shutterLevel) }
And in the
onValueChangeFinished
event, I pass it to the API to control the device. This all works as expected, but... I also listen to events from the server. So whenever the brightness is changed through another app or the shutter level is modified with the wall switch, the
Slider
position does not change because it was `remember`ed. I would be really happy if anyone could help me understand what I am missing here.
1
t

tad

04/07/2022, 9:05 PM
This is a "source-of-truth" problem. Right now you are telling Slider that the source of truth is your remembered
State
variable, so that's what it will use. I would read up on state hoisting so you can have a common source of truth that is updated from both your Composable function and whatever external event you are observing.
t

trashcoder

04/07/2022, 9:22 PM
First of all: Thanks for your quick response! I use Decompose and have all state hoisted in components. But without the local variable, it was a bit laggy when dragging the
Slider
. Maybe I should further investigate the "Laggyness" then. Thanks!
t

tad

04/07/2022, 9:27 PM
The intermediate value can still be stored in a local variable, it will just need to be recomposed when the hoisted state changes. You can do this by passing a
key
argument to remember, e.g.
remember(shutter.shutterLevel) { mutableStateOf(shutter.shutterLevel) }
and tell
shutter
to update itself directly in
onValueChangeFinished
t

trashcoder

04/07/2022, 9:35 PM
I only had to add the
key
to
remember
and now it works! :mind-blown: Thanks a lot! 🥳 🙏
t

tad

04/07/2022, 9:36 PM
Nice, no problem.