*Is there anything like `RecyclerView`’s `StateRes...
# compose
j
Is there anything like `RecyclerView`’s
StateRestorationPolicy.PREVENT_WHEN_EMPTY
for
LazyColumn
?
LazyColumn
doesn’t currently restore the scroll position if the list’s data is fed using something like
val myList by aFlow.collectAsState(emptyList())
. For example during configuration changes (like rotation, dark/light theme switch, etc.) the flow will be resubscribed to and so
aFlow
will temporarily emit
emptyList()
causing the saved scroll position to be discarded. This is a workaround I found but I was hoping it could be handled better:
Copy code
if (myList.isNotEmpty()) {
    LazyColumn() {
       // .....
    }
}
i
Generally, you should avoid the latency of requerying from scratch in the first place by using
shareIn
inside a ViewModel, thus ensuring that your last data is immediately available after a config change, skipping the whole empty list problem entirely
j
Definitely, although
ViewModel
only helps for configuration changes but not for system initiated process death (SIPD). I was looking for a solution that could encompass both. Throwing in a ViewModel to optimize the configuration change part is always a nice to have and can be done with little effort. In other words: if one solves the SIPD side, the configuration change side gets taken care of implicitly.
a
could you file a bug for this feedback? so at least we consider this in the future. but in general I don’t think the solution with if is that bad
👌 1
a
@Ian Lake I don't think
shareIn
works because when using
collectAsState()
on flows other than `StateFlow`s you always have to specify an initial value and that initial value will always be used even if the flow emits immediately. In my app I'm using
collectAsState()
on a flow produced by transforming the value of
StateFlow
in a ViewModel and I'm facing the same problem. I have tried
shareIn
and it didn't work.
i
Sure, you can use
stateIn
then