Hi, I would like to scroll to top when I update my...
# compose
r
Hi, I would like to scroll to top when I update my
LizyColumn
data (on refresh), here is how I did it
Copy code
LaunchedEffect(state.receipts) {
    if (state.receipts.isNotEmpty()) {
        listState.scrollToItem(0)
    }
}
but it doesn't always work, its always called, but it doesn't scroll, and my guess here is that the
LazyColumn
hasn't rendered/updated its content yet at this point so it scrolls in the old list, then updates the list with new data, if I put a
delay(500)
before calling
scrollToItem
it works, but I don't wanna put some random value, that might not work for slower devices, any advise here?
example of what happens:
Copy code
old list:
receipt x <--- first visible item
receipt y
receipt z

new list after refresh:
receipt a
receipt x <--- still first visible item, I have to scroll up to see `a`
receipt y
receipt z
l
I think it would be simpler if you put an empty item at the beginning, so that the anchoring is done on this one and you'll see your new items appear at the beginning of your list
item {}
r
hmmm
this kinda makes sense, but it feels hacky xD
l
The only difference is that it only works if you're already at the top of the list (and not if you've already scrolled).
r
I think it will work with my above
scroll to item 0
even if we're at the middle cuz if my call happens before rendering the new list, the empty item will become first and then stay first, and if my call happens after rendering the list, then it will scroll correctly, let me give it a try
it actually worked 😄 I'll keep it for now till I find a better solution thats intuitively understandable, I'm sure I'll be confused in the future of why I have this empty item
r
oh thanks for sharing @Dmitry Strekha! I did try
requestScrollToItem
but it had the same issue, I guess what I did wrong was using LaunchEffect rather than SideEffect which runs AFTER the composition is done, while LaunchEffect actually ran at the beginning of the composition so it was getting invoked before the list gets the state change
e
LaunchedEffect does not run at the beginning of (or before) composition. Its also run after composition.