I recently added a `LazyListState` property to a v...
# compose-android
m
I recently added a
LazyListState
property to a view model to preserve the scroll position of a
LazyColumn
through config changes. However, LeakCanary seems to imply this is causing a memory leak. Any ideas?
f
LazyColumn
scroll position should be automatically preserved through it's usage of
rememberSaveable
🤔 So putting it in your VM should not be necessary. Not sure about the leak tho 🤷
thank you color 1
m
Ah yes, you’re right. I was originally playing with having the state in the view model because
rememberLazyListState
wasn’t working for me, but later realised that was because I was collecting
LazyColumn
items from a flow where the
initialValue
was empty and so the state became invalid (0 items). My workaround for this now is to use a dummy state corresponding to when the item state is
initialValue
. Anyway, the memory leak is now gone, so thanks very much.
f
No worries 🤝 I am glad I could've helped
🤝 1
m
Hmm, this seems super weird but can this be achieved with something like:
Copy code
val lazyListState = if (items == null) {
    // use a dummy list state until we get a real items
    rememberLazyListState()
} else {
    rememberLazyListState()
}
f
Ouch 😅 But hey, if it works...
m
Haha, it seems to…
s
For future reports, LeakCanary usually provides a backtrace with fields that caused a leak, which might be useful for debugging. About lazy list state, you don't really need to recreate state, just
scrollToItem
whenever items change. It also should work with incorrect indices as well
m
Thanks Andrei, yes LC pointed me to the
LazyListState
property in my viewmodel, which is what brought my attention to this. I’m not getting any more LC reports, so it seems fixed now. The composable collects a flow from the
ViewModel
so I think there is always going to be a moment where the
initialValue
is being used. It seems the
LazyListState
is updated (to item zero) by the
LazyColumn
when the initial content is empty.