'Scroll Two Lazy Scrollers Together

This question has been asked before, but in different forms, regarding some specific use cases, and so far there has been no answer. I finally got it working, so I am sharing this here, but this should not be marked as a duplicate since all the previous questions specify specific stuff, like Columns with scrollable Modifiers, or LazyRows, but this will resolve all the issues in general, I mean all the lazy-scrollers, and hopefully even scrollable containers in general. I'll post the answer so this is just a piece of knowledge that I wished to share with the community, also, any improvements are welcome, of course.



Solution 1:[1]

The above answer by Richard is good but it creates lags when scrolling because of the loop it creates as described by Ivan. The solution is simple for that problem

LaunchedEffect(stateRowX.firstVisibleItemScrollOffset) {
    if (!stateRowY.isScrollInProgress) {
        stateRowY.scrollToItem(
            stateRowX.firstVisibleItemIndex,
            stateRowX.firstVisibleItemScrollOffset
        )
    }
}

LaunchedEffect(stateRowY.firstVisibleItemScrollOffset) {
    if (!stateRowX.isScrollInProgress) {
        stateRowX.scrollToItem(
            stateRowY.firstVisibleItemIndex,
            stateRowY.firstVisibleItemScrollOffset
        )
    }
}

Now it will not lag while scrolling.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sunny