nglauber
12/16/2021, 1:57 PMLazyColumn
scroll state after navigate to a different screen? I’m getting a strange behavior…
val listState = rememberLazyListState()
val reportList by viewModel.reportList.flowInLifecycle()
.collectAsState(initial = emptyList())
The code above is in ScreenA
, from this screen I open ScreenB
. When I return to ScreenA
, the reportsList
becomes empty for 1 composition, so the listState
moves to position 0.Zach Klippenstein (he/him) [MOD]
12/16/2021, 3:07 PMflowInLifecycle()
defined? Assuming it’s a composable that correctly remembers the transformed flow, if viewModel.reportList
is a StateFlow
then flowInLifecycle
should also return a StateFlow
so that you can use the overload of collectAsState
that takes its initial value from the actual flow.nglauber
12/16/2021, 3:09 PM@Composable
fun <T> Flow<T>.flowInLifecycle(): Flow<T> {
val lifecycleOwner = LocalLifecycleOwner.current
return remember(this, lifecycleOwner) {
this.flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED)
}
}
JulianK
12/16/2021, 3:34 PM@Composable
fun <T> StateFlow<T>.collectAndRemember(): State<T> =
flowInLifecycle(this).collectAsState(initial = this.value)
Zach Klippenstein (he/him) [MOD]
12/16/2021, 4:19 PMcollectAndRemember
looks more like what i think you’d wantnglauber
12/16/2021, 6:08 PMflowInLifecycle
?JulianK
12/17/2021, 8:51 AM@Composable
fun <T> rememberFlowWithLifecycle(
flow: Flow<T>,
lifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED
): Flow<T> = remember(flow, lifecycle) {
flow.flowWithLifecycle(
lifecycle = lifecycle,
minActiveState = minActiveState
)
}
@Composable
fun <T> StateFlow<T>.collectAndRemember(): State<T> =
rememberFlowWithLifecycle(this).collectAsState(initial = this.value)
nglauber
12/17/2021, 11:29 AM