https://kotlinlang.org logo
#compose-android
Title
# compose-android
m

Mark

11/30/2023, 11:08 AM
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

Filip Wiesner

11/30/2023, 11:11 AM
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

Mark

11/30/2023, 11:25 AM
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

Filip Wiesner

11/30/2023, 11:26 AM
No worries 🤝 I am glad I could've helped
🤝 1
m

Mark

11/30/2023, 11:31 AM
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

Filip Wiesner

11/30/2023, 11:35 AM
Ouch 😅 But hey, if it works...
m

Mark

11/30/2023, 11:35 AM
Haha, it seems to…
s

shikasd

11/30/2023, 2:11 PM
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

Mark

12/03/2023, 8:27 AM
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.
2 Views