Hi everyone! I have created a horizontal pager wit...
# compose-android
p
Hi everyone! I have created a horizontal pager with an infinite auto scrolling behavior. So that I use the launched effect to have the automatically scrolling the pages. However, the coroutine seems to be cancelled and the scrolling has been stopped after I scroll the pages manually. Could you please give me the advices to fix this ? Thanks a lot. Here is my pager implementation:
Copy code
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AdsComposeUi(
    adsLiveData: LiveData<List<Ads>>,
    onAdsClicked: (Ads) -> Unit = {},
) {
    val adsState = adsLiveData.observeAsState()
    adsState.value?.let {
        if (it.isNotEmpty()) {
            // We start the pager in the middle of the raw number of pages
            val startIndex = Int.MAX_VALUE / 2
            val pagerState = rememberPagerState(initialPage = startIndex)
            val pageCount = it.size

            Box(
                modifier = Modifier
                    .wrapContentSize()
                    .padding(horizontal = 16.dp, vertical = 10.dp)
            ) {
                HorizontalPager(
                    state = pagerState,
                    pageCount = Int.MAX_VALUE,
                    modifier = Modifier.wrapContentSize()
                ) { index ->
                    val page = Math.floorMod(index - startIndex, pageCount)
                    AdsBannerUi(url = it[page].url) {
                        onAdsClicked(it[page])
                    }
                }
            }

            LaunchedEffect(key1 = pagerState) {
                while (isActive) {
                    delay(3000L)
                    if (!isActive) break
                    pagerState.animateScrollToPage(
                        (pagerState.currentPage + 1) % pageCount
                    )
                }
            }
        }
    }
}
d
What is
isActive
?
It might have become false when you started scrolling, perhaps?
Do you need to add it as a key to the LaunchedEffect?
s
isActive
is from the coroutine itself, in this scenario it would be false only when the coroutine gets cancelled, aka when pagerState changes or if this composable leaves composition. https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/is-active.html
p
Yeah I agree. However, I'm expecting the coroutine restarted but it's not if I scrolled it manually.
191 Views