DEV Community

myougaTheAxo
myougaTheAxo

Posted on • Originally published at zenn.dev

Coil Image Loading for Android - AsyncImage and Caching (v2)

Coil simplifies image loading in Compose. Learn AsyncImage, caching strategies, and SubcomposeAsyncImage for advanced use cases.

Basic AsyncImage Usage

Load and display images with one line:

AsyncImage(
    model = "https://example.com/image.jpg",
    contentDescription = "Profile picture",
    modifier = Modifier
        .size(128.dp)
        .clip(CircleShape),
    contentScale = ContentScale.Crop
)
Enter fullscreen mode Exit fullscreen mode

Configuring Image Loading with ImageRequest

Customize loading behavior:

val imageRequest = ImageRequest.Builder(context)
    .data("https://example.com/image.jpg")
    .crossfade(true)
    .placeholder(R.drawable.placeholder)
    .error(R.drawable.error)
    .build()

AsyncImage(
    model = imageRequest,
    contentDescription = "Article image",
    modifier = Modifier.fillMaxWidth(),
    contentScale = ContentScale.Crop
)
Enter fullscreen mode Exit fullscreen mode

Custom Caching Strategy

Optimize memory and disk usage:

// In Application class
val imageLoader = ImageLoader.Builder(context)
    .memoryCache {
        MemoryCache.Builder(context)
            .maxSizePercent(0.25)  // Use 25% of memory
            .build()
    }
    .diskCache {
        DiskCache.Builder()
            .directory(File(context.cacheDir, "image_cache"))
            .maxSizeBytes(100 * 1024 * 1024)  // 100 MB
            .build()
    }
    .build()

Coil.setImageLoader(imageLoader)
Enter fullscreen mode Exit fullscreen mode

SubcomposeAsyncImage for Complex Layouts

Handle loading, success, and error states:

SubcomposeAsyncImage(
    model = "https://example.com/image.jpg",
    contentDescription = "Product image",
    modifier = Modifier.fillMaxSize()
) { state ->
    when (state) {
        is AsyncImagePainter.State.Loading -> {
            CircularProgressIndicator()
        }
        is AsyncImagePainter.State.Success -> {
            Image(
                painter = state.painter,
                contentDescription = null,
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop
            )
        }
        is AsyncImagePainter.State.Error -> {
            Icon(Icons.Default.Error, "Error loading image")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Coil's efficient loading and caching improve app performance. Use SubcomposeAsyncImage when you need custom loading states.

8 Android app templates on Gumroad

Top comments (0)