Android:Cache Validity for an Image using coil in jetpack
Asked Answered
F

1

7

I am facing issue in setting validity for Cache in android jetpack using coil. What I Need: In Android Jetpack compose, I need to download an SVG image from the Url and store it to the cache. But the cache should store the image only for 20 seconds. so within the 20 seconds, there should not be any further image request. For this 20 seconds, the image should display from the cache. After 20 seconds, I want the image, should get cleared from the cache.

What's the problem I am facing: The image is not getting cleared from the cache even after 20 seconds. I am using Coil for the jetpack compose jetpack coil and Jetpack header for Cachecontrol Thanks in Advance....

In Application Class, I created a single instance ImageLoader

val imageLoader = ImageLoader.Builder(applicationContext)
            .componentRegistry {
                add(SvgDecoder(applicationContext))
            }
            .okHttpClient {
                OkHttpClient.Builder()
                        .cache(CoilUtils.createDefaultCache(applicationContext))
                        .addNetworkInterceptor(provideCacheInterceptor(10))
                        .build()

            }
            .memoryCachePolicy(CachePolicy.DISABLED)
            .diskCachePolicy(CachePolicy.ENABLED)
            .build()

    Coil.setImageLoader(imageLoader = imageLoader)

In Moment.class:

val singleInstanceImageLoader = context.imageLoader
val imageRequest = ImageRequest.Builder(context)
                .data(decodedURL)
                .memoryCachePolicy(CachePolicy.DISABLED)
                .diskCachePolicy(CachePolicy.ENABLED)
               .addHeader("Cache-Control", "max-age=20,public")
               .build()

        val imagePainter = rememberCoilPainter(
                request = imageRequest,
                imageLoader = singleInstanceImageLoader
        )

        Image(
                painter = imagePainter,
                contentDescription = null,
                modifier = Modifier
                        .wrapContentSize(Alignment.Center)
                        .padding(0.dp, 15.dp, 0.dp, 15.dp)

        )
Feat answered 9/9, 2021 at 17:44 Comment(4)
create an issue on Coil githubOtho
I created an issue on coil GitHub, thanks @PhilipDukhovFeat
Not sure why you are commenting here. You should add your updated code as a comment to your coil issue. Maybe you are still doing something wrong or it really is a bug.Otho
Am facing same issueDevisor
F
2

I got a reply from coil:

This isn't a bug. Looking at your code, you're setting the cache-control header for the request. You need to set it for the response using a network interceptor.

But I tried this approach and it also didn't work.

Hope this might be useful for someone else though.

Feat answered 14/1, 2022 at 17:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.