Hi, Facing issue with loading new images in `LazyC...
# compose
a
Hi, Facing issue with loading new images in
LazyColumn
. Existing image shows until new image is available. It's using Coil's
ImageLoader
and
produceState
. Details in the 🧵
Copy code
@Composable
fun loadNetworkImage(
    url: String,
    imageLoader: ImageLoader = LocalContext.current.imageLoader,
): State<Result> {
    val context = LocalContext.current
    return produceState<Result>(initialValue = Result.Loading, url, imageLoader) {
        val imageRequest = ImageRequest.Builder(context).data(url).build()
        val image = imageLoader.execute(imageRequest).drawable
        value = if (image == null) {
            Result.Error
        } else {
            Result.Success(image)
        }
    }
}

sealed class Result {
    object Loading : Result()
    object Error : Result()
    data class Success(val data: Drawable) : Result()
}

LazyColumn {
    items(imageUrls) { imageUrl ->
        when (val result = loadNetworkImage(imageUrl).value) {
            is Result.Loading -> {
                Text(
                    "Loading",
                    modifier = Modifier
                        .size(128.dp)
                        .background(Color.LightGray)
                        .wrapContentSize(Alignment.Center)
                )
            }
            is Result.Success -> {
                val data = result.data
                Image(
                    painter = BitmapPainter(data.toBitmap().asImageBitmap()),
                    contentDescription = null,
                    modifier = Modifier.size(128.dp),
                )
            }
            is Result.Error -> {
                Text(
                    "Error",
                    modifier = Modifier
                        .size(128.dp)
                        .background(Color.LightGray)
                        .wrapContentSize(Alignment.Center)
                )
            }
        }
    }
}
c
Maybe file a bug on coils repo? The maintainer is always super responsive there.
a
try to specify keys for your items, it is a separate lambda on items function. this will help when because of addition your item position changes. right now the item for the new first item is composed over the item displaying the old first item
a
Thanks Andrey! This works but now issue is need to programmatically handle scrolling. is there a better way to handle it?
Copy code
val listState = rememberLazyListState()
LaunchedEffect(key1 = imageUrls.size) {
    listState.animateScrollToItem(index = 0)
}
LazyColumn(state = listState)  {
    items(imageUrls, key = {it}) { imageUrl ->
...
}
a
unfortunately there is no better way yet. this bug is tracking it - https://t.co/MZJU2yxH8q
a
Thanks, will keep eye on it 👍