Zoltan Demant
09/09/2022, 9:36 AMLaunchedEffect(list.size){ scrollToTop() }
in order to scroll my LazyColumn
to the top whenever the list size changes. This works great, but it also scrolls the list to the top whenever I navigate back to it since the LaunchedEffect is restarted. I could work around this with rememberSaveable
, but that doesnt seem ideal. Is there another better approach?Albert Chang
09/09/2022, 10:32 AMlist
instance change? If it doesn't change, you can use something like:
LaunchedEffect(list) {
snapshotFlow { list.size }.drop(1).collect {
scrollToTop()
}
}
Zoltan Demant
09/09/2022, 10:33 AMLaunchedEffect
starts anew everytime the screen re-enters the composition (e.g. when navigating back to it).Albert Chang
09/09/2022, 10:34 AMdrop(1)
.Zoltan Demant
09/09/2022, 10:35 AM@Composable
inline fun <T : Any> RememberEffect(
value: T,
crossinline action: suspend () -> Unit,
) {
val scope = rememberCoroutineScope()
rememberSaveable(value) {
value.also {
scope.launch { action() }
}
}
}
@Composable
fun <T> ScrollToTop(
controller: ListController,
key: T,
) {
val updatedKey by rememberUpdatedState(key)
LaunchedEffect(Unit) {
snapshotFlow { updatedKey }
.drop(1)
.collect {
controller.scrollToTop(
animated = true,
)
}
}
}