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

zsperske

06/23/2022, 4:32 PM
I’m trying to make the scroll position of my Composable available in the View world, but I’m having trouble.
Copy code
//I create a scroll state in my view model and pass it here to be used
val scrollState = rememberSaveable(saver = ScrollState.Saver) { viewModel.state.scrollState }

//Add to my column
Modifier.verticalScroll(scrollState)

//In on save instance state of an Android View I grab the state and save it to a bundle
savedState.scrollPosition = viewModel.state.scrollState.value
However, the scroll state’s value is always 0. Am I going about this all wrong?
c

chatterInDaSkull

06/23/2022, 4:41 PM
My hunch is you are missing a
rememberScrollState()
somewhere
z

zsperske

06/23/2022, 4:42 PM
I had tried to do that manually by doing:
val scrollState = rememberSaveable(saver = ScrollState.Saver) { viewModel.state.scrollState }
I can’t do
rememberScrollState
since I need to create the scroll state in my view model
c

chatterInDaSkull

06/23/2022, 4:55 PM
can you undo your
rememberSaveable
and simply use
rememberScrollState()
and manually set
viewModel.state.scrollState = scrollState.value
and try it out? probably not good for performance and might incur a lot of recompositions but still might help validate something
z

zsperske

06/23/2022, 5:09 PM
interesting that does capture the value correctly
but I agree that this isn’t optimal, I don’t want it to solve it this way
c

chatterInDaSkull

06/23/2022, 5:11 PM
I don’t think this is entirely wrong fyi, you could set your view model state by using
derivedStateOf
to optimize a bit Out of curiosity, what does your view model look like with respect to the scroll state? how is it defined?
also i’m not sure if you know but
rememberSaveable(saver = ScrollState.Saver) { viewModel.state.scrollState }
is only giving it an initial state, I think it creates new scroll state objects (once again easily verifiable)
z

zsperske

06/23/2022, 6:17 PM
view model looks like this
Copy code
class ViewModel() {
   var state by mutableStateOf(MyState())
    private set

   fun updateScrollPosition(position: Int) {
      state = state.copy(scrollState = ScrollState(position)
   }
}

data class MyState(val scrollState: ScrollState, ...)
To test your theory I temporarily made the
scrollState
a
var
which breaks recomposition. But if I were to change it to instead have a
updateScrollState
method I think I’d end up in an endless loop of recomposition
(testing that now)
while things get saved correctly, and I make a call to update the scroll position after restoring the state, the view doesn’t scroll
Copy code
val scrollState = rememberScrollState(viewModel.state.scrollPosition)
viewModel.updateScrollState(scrollState)
c

chatterInDaSkull

06/23/2022, 7:29 PM
are there many many recompositions per scroll event?
3 Views