androidandroid-jetpack-compose

How to prevent AsyncImage from using cached images?


I'm using Coil library in Jetpack Compose to load images from network with AsyncImage. However, I noticed that AsyncImage caches the image, so if the same URL is used again, it loads from the cache instead of fetching the updated image.

This causes an issue in my case because the image at the URL may have changed, but AsyncImage still displays the old cached version.

How can I prevent AsyncImage from using cached images and force it to always load the latest version?


Solution

  • For your use-case, you can disable cache policy as below:

    @Composable
    fun FreshImage(url: String) {
        val context = LocalContext.current
    
        AsyncImage(
            model = ImageRequest.Builder(context)
                .data(url)
                .diskCachePolicy(CachePolicy.DISABLED)    
                .memoryCachePolicy(CachePolicy.DISABLED) 
                .build(),
            contentDescription = "Fresh image"
        )
    }
    

    You can solve your issue by updating the cache policy. For more details, please refer to this answer by @Phil Dukhov for an in-depth explanation of Coil's caching.