Jetpack Compose Image Loading — Complete Guide
In this tutorial, you'll learn about Jetpack Compose Image Loading. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Loading an image from a URL blocks the UI, causes OutOfMemoryError, or shows blank space while downloading.
Wrong Approach ❌
@Composable
fun BadImage(url: String) {
// Blocking network on main thread — ANR!
val bitmap = URL(url).readBytes().let { BitmapFactory.decodeByteArray(it, 0, it.size) }
Image(bitmap = bitmap.asImageBitmap(), contentDescription = "Photo")
}
@Composable
fun NoPlaceholder(url: String) {
// Coil without placeholder — shows blank during load
AsyncImage(model = url, contentDescription = "Photo")
}
Output: NetworkOnMainThreadException or blank UI during loading.
Right Approach ✅
@Composable
fun GoodImage(url: String) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(url)
.crossfade(true)
.size(Size(400, 400)) // Resize to avoid OOM
.memoryCachePolicy(CachePolicy.ENABLED)
.build(),
contentDescription = "User photo",
modifier = Modifier
.size(200.dp)
.clip(CircleShape),
placeholder = painterResource(R.drawable.placeholder),
error = painterResource(R.drawable.error),
contentScale = ContentScale.Crop
)
}
// For custom composable image loading
@Composable
fun CustomImageLoader(url: String) {
val painter = rememberAsyncImagePainter(
model = ImageRequest.Builder(LocalContext.current)
.data(url)
.size(Size.ORIGINAL)
.build()
)
Image(
painter = painter,
contentDescription = "Photo",
modifier = Modifier.fillMaxWidth()
)
}
Output: Smooth async loading with placeholders, Caching, and OOM prevention.
Prevention
- Always use
AsyncImageorrememberAsyncImagePainterfrom Coil. - Set
sizeonImageRequestto downsample large images. - Provide
placeholderanderrorpainter resources. - Enable
crossfade(true)for smooth transitions.
Common Mistakes with compose image load
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro