Search code examples
androidandroid-jetpack-composecoil

How do I set Coil to get Image from the local cache if available instead of fetching it from the network


I am using Coil version "coil-compose:2.2.2".

Problem: I want Coil to populate an image from the local cache when available instead of fetching it from the network.

Current Behaviour: At the moment Coil retrieves the local cache only when there is no internet.

Expected Behaviour: I want Coil to use the local cache(if it exists) even when the internet is available. And Only if local cache does not exist then fetch it from the network. How do I achieve this?

Here is my current implementation:

ImageRequest.Builder(context)
.data(imageUrl)
.networkCachePolicy(CachePolicy.ENABLED)
.diskCachePolicy(CachePolicy.ENABLED)
.memoryCachePolicy(CachePolicy.ENABLED)
.diskCacheKey(imageUrl)
.memoryCacheKey(imageUrl)
.size(Size.ORIGINAL)
.build()

Solution

  • You haven't set the disk cache, do this instead.

    ImageRequest.Builder(context)
        .data(imageUrl)
        .diskCache {
            DiskCache.Builder()
                .directory(context.cacheDir.resolve("image_cache"))
                .maxSizePercent(0.02)
                .build()
        }
        .size(Size.ORIGINAL)
        .build()
    

    But if you have many image request builders, it's recommended to set the cache globally so you wouldn't need to set it anywhere again.

    Open your MainApplication class, extends it with ImageLoaderFactory and override method newImageLoader

    class MainApplication : Application(), ImageLoaderFactory {
        override fun newImageLoader(): ImageLoader {
            return ImageLoader.Builder(this)
                .diskCache {
                    DiskCache.Builder()
                        .directory(context.cacheDir.resolve("image_cache"))
                        .maxSizePercent(0.02)
                        .build()
                }
                .build()
        }
    }
    

    References: