Is it possible to synchronize the `LazyListState` ...
# compose
z
Is it possible to synchronize the
LazyListState
(scroll position) between multiple
LazyRow
? Ive tried using one
rememberLazyListState
but that results in weird scrolling glitches; Im sort of assuming that Ill need to collect all scroll events and update each
LazyListState
?
c
LazyListState
contains all of the layout state for its host component, so it can only really be used in a single
LazyColumn
, etc. I wouldn’t mess around with touch input here. I’d use a
LaunchedEffect
to read the first visible item + offset on each
LazyListState
, then call
scrollToItem
to coordinate the others. You might need to gate the changes on
isScrollInProgress
to stop any recursion loops.
z
Thanks Chris, Ill try that when I get back to working on this feature! 👍🏽
👍 1
Aaand it works! 🙂 Thanks again.
Copy code
val listControllers = remember {
    mutableStateMapOf<ChartType, ListController>()
}

LaunchedEffect(listControllers) {
    val controllers = listControllers.values

    snapshotFlow {
        controllers
            .firstOrNull(ListController::scrollInProgress)
            ?.let { controller ->
                val index = controller.firstVisibleItemIndex()
                val scrollOffset = controller.firstVisibleItemScrollOffset()
                index to scrollOffset
            }
    }
        .filterNotNull()
        .distinctUntilChanged()
        .collect { (index, scrollOffset) ->
            controllers.forEach { controller ->
                if (!controller.scrollInProgress()) {
                    controller.scrollTo(
                        index,
                        scrollOffset
                    )
                }
            }
        }
}
c
Very nice! Glad it worked 😅
🥲 1
@Andrey Kulikov in case there’s a better way
137 Views