I’m trying to make the scroll position of my Compo...
# compose
z
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
My hunch is you are missing a
rememberScrollState()
somewhere
z
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
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
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
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
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
are there many many recompositions per scroll event?