0

Pause image loading in coil onscroll in lazycolumn in jetpack compose android

We are using Coil to load images with jetpack compose , earlier in glide with recylerview or other lists we had the option to pause loading images when we scrolled , it was an efficient way to prevent lag on scroll , Is there any way to achieve this.

1234567
  • 2,226
  • 4
  • 24
  • 69

2 Answers2

0

As per the guide, in Coil 2.x they have already managed this. According to this section of the guide

screenshot

Infact, this was one of the issue in coil 2.0 where it didn't cancelled the request when the scoped was cancelled. This issue was resolved.

0

You can check if the item is visible you can load the image otherwise don't load it.

val state = rememberLazyListState()
val fullyVisibleIndices: List<Int> by remember {
    derivedStateOf {
        val layoutInfo = state.layoutInfo
        val visibleItemsInfo = layoutInfo.visibleItemsInfo
        if (visibleItemsInfo.isEmpty()) {
            emptyList()
        } else {
            val fullyVisibleItemsInfo = visibleItemsInfo.toMutableList()

            val lastItem = fullyVisibleItemsInfo.last()

            val viewportHeight = layoutInfo.viewportEndOffset + layoutInfo.viewportStartOffset

            if (lastItem.offset + lastItem.size > viewportHeight) {
                fullyVisibleItemsInfo.removeLast()
            }

            val firstItemIfLeft = fullyVisibleItemsInfo.firstOrNull()
            if (firstItemIfLeft != null && firstItemIfLeft.offset < layoutInfo.viewportStartOffset) {
                fullyVisibleItemsInfo.removeFirst()
            }

            fullyVisibleItemsInfo.map { it.index }
        }
    }
}
LazyColumn(
    state = state,
    contentPadding = PaddingValues(30.dp)
) {
    items(100) { index -> 
        val isVisible by remember(index) {
            derivedStateOf {
                fullyVisibleIndices.contains(index)
            }
        }
        Text(
            index.toString(),
            modifier = Modifier
                .background(if (isVisible) Color.Green else Color.Transparent)
                .padding(30.dp)
        )
    }
}
Chirag Thummar
  • 665
  • 6
  • 16