Skip to content

Instantly share code, notes, and snippets.

@rahulsainani
Last active May 20, 2021 16:22
Show Gist options
  • Save rahulsainani/55bc478371d4cb3204b5712521b1578c to your computer and use it in GitHub Desktop.
Save rahulsainani/55bc478371d4cb3204b5712521b1578c to your computer and use it in GitHub Desktop.
@Composable
fun <T : Any> AutoScrollingLazyRow(
list: List<T>,
modifier: Modifier = Modifier,
scrollDx: Float = SCROLL_DX,
delayBetweenScrollMs: Long = DELAY_BETWEEN_SCROLL_MS,
divider: @Composable () -> Unit = { Spacer(modifier = Modifier.width(Dimens.grid_1)) },
itemContent: @Composable (item: T) -> Unit,
) {
var itemsListState by remember { mutableStateOf(list) }
val lazyListState = rememberLazyListState()
LazyRow(
state = lazyListState,
modifier = modifier,
) {
items(itemsListState) {
itemContent(item = it)
divider()
if (it == itemsListState.last()) {
val currentList = itemsListState
val secondPart = currentList.subList(0, lazyListState.firstVisibleItemIndex)
val firstPart = currentList.subList(lazyListState.firstVisibleItemIndex, currentList.size)
rememberCoroutineScope().launch {
lazyListState.scrollToItem(0, maxOf(0, lazyListState.firstVisibleItemScrollOffset - scrollDx.toInt()))
}
itemsListState = firstPart + secondPart
}
}
}
LaunchedEffect(Unit) {
autoScroll(lazyListState, scrollDx, delayBetweenScrollMs)
}
}
private tailrec suspend fun autoScroll(
lazyListState: LazyListState,
scrollDx: Float,
delayBetweenScrollMs: Long,
) {
lazyListState.scroll(MutatePriority.PreventUserInput) {
scrollBy(scrollDx)
}
delay(delayBetweenScrollMs)
autoScroll(lazyListState, scrollDx, delayBetweenScrollMs)
}
private const val DELAY_BETWEEN_SCROLL_MS = 8L
private const val SCROLL_DX = 1f
AutoScrollingLazyRow(list = featuresList) {
FeatureTile(feature = it)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment