Patrick-GGX
07/14/2023, 3:48 AM@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
)
}
}
}
}
}
Deji Akande
07/14/2023, 6:39 PMisActive
?Deji Akande
07/14/2023, 6:39 PMDeji Akande
07/14/2023, 6:40 PMStylianos Gakis
07/14/2023, 6:51 PMisActive
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.htmlPatrick-GGX
07/15/2023, 12:59 AM