Coil — Place holder and error image
Curiosly there are two ways to add placeholder and error image on coil. You can specify it either on the model or on the Asynch Image itself:
AsyncImage(
model = ImageRequest
.Builder(LocalContext.current)
.data(imageUrl)
.crossfade(true)
.build(),
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1400f/800f),
placeholder = painterResource(R.drawable.coillogo),
error = painterResource(R.drawable.coillogo)
)AsyncImage(
model = ImageRequest
.Builder(LocalContext.current)
.data(imageUrl)
.crossfade(true)
.placeholder(R.drawable.coillogo)
.error(R.drawable.coillogo)
.build(),
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1400f/800f),
)Of course, if you set the model as url, this will also work
AsyncImage(
model = imageUrl,
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1400f/800f),
placeholder = painterResource(R.drawable.coillogo),
error = painterResource(R.drawable.coillogo)
)Now, based on my actual experience on prod, if you are using ImageRequest , it is better to set the place holder and the error image on the ImageRequest itself. Otherwise there might be bitmap duplicated in the App heap (I saw it once, not consistent thou)
Get Switch your coding life’s stories in your inbox
Join Medium for free to get updates from this writer.
Source code: https://github.com/jiahaoliuliu/CoilImageCaching/tree/placeHoldersAndErrorImages









