aniruddha dhamal
04/16/2022, 5:10 PMLazyColumn
. Existing image shows until new image is available. It's using Coil's ImageLoader
and produceState
. Details in the 🧵aniruddha dhamal
04/16/2022, 5:10 PM@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)
)
}
}
}
}
Colton Idle
04/19/2022, 3:44 AMAndrey Kulikov
04/20/2022, 10:46 PManiruddha dhamal
04/20/2022, 10:57 PMval listState = rememberLazyListState()
LaunchedEffect(key1 = imageUrls.size) {
listState.animateScrollToItem(index = 0)
}
LazyColumn(state = listState) {
items(imageUrls, key = {it}) { imageUrl ->
...
}
Andrey Kulikov
04/20/2022, 11:04 PManiruddha dhamal
04/20/2022, 11:08 PM