Search code examples
androidandroid-jetpack-composecoiljetpack-compose-accompanist

Coil image caching not working with Jetpack Compose


I am using coil(version 2.1.0) to load images from URL. When there is network connection, the images are loading fine. However, when there is no network connection, the images are not being pulled from the cache as I expected them. Here's a block of code I have.

class App : Application(), ImageLoaderFactory {

    override fun newImageLoader(): ImageLoader {
       return ImageLoader.Builder(this)
            .memoryCache {
                MemoryCache.Builder(this)
                    .maxSizePercent(0.25)
                    .build()
            }
            .diskCache {
                DiskCache.Builder()
                    .directory(cacheDir.resolve("image_cache"))
                    .maxSizeBytes(5 * 1024 * 1024)
                    .build()
            }
            .build()
    }
  }

In Compose:

                val context = LocalContext.current
                val placeholderImage = R.drawable.ic_placeholder
    
                val imageRequest = ImageRequest.Builder(context)
                    .data(imageUrl)
                    .memoryCacheKey(imageUrl)
                    .diskCacheKey(imageUrl)
                    .placeholder(placeholderImage)
                    .error(placeholderImage)
                    .fallback(placeholderImage)
                    .diskCachePolicy(CachePolicy.ENABLED)
                    .memoryCachePolicy(CachePolicy.ENABLED)
                    .transformations(CircleCropTransformation())
                    .build()

                AsyncImage(
                    model = imageRequest,
                    modifier = Modifier.size(64.dp),
                    contentDescription = null,
                    imageLoader = context.imageLoader
                )

When the device is offline, it only loads the placeholder image instead of the image from cache as expected. What am I missing here?


Solution

  • I used logger(DebugLogger()) in ImageLoader to figure out what was going on and I found out that app was running into HTTP 504 error when Coil was trying to load image offline. So I added .respectCacheHeaders(false) to the ImageLoader. That seemed to do the trick for me.

    Hope this helps someone else running into similar problem.