https://kotlinlang.org logo
#compose
Title
# compose
a

aniruddha dhamal

04/16/2022, 5:10 PM
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

Colton Idle

04/19/2022, 3:44 AM
Maybe file a bug on coils repo? The maintainer is always super responsive there.
a

Andrey Kulikov

04/20/2022, 10:46 PM
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

aniruddha dhamal

04/20/2022, 10:57 PM
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

Andrey Kulikov

04/20/2022, 11:04 PM
unfortunately there is no better way yet. this bug is tracking it - https://t.co/MZJU2yxH8q
a

aniruddha dhamal

04/20/2022, 11:08 PM
Thanks, will keep eye on it 👍
2 Views