coil-kt / coil

Image loading for Android and Compose Multiplatform.
https://coil-kt.github.io/coil/
Apache License 2.0
10.78k stars 660 forks source link

DiskCache gets reset on app restart #1447

Closed jikyu closed 2 years ago

jikyu commented 2 years ago

Describe the bug My app loads images and caches them to DiskCache without any issues. Queries like context.imageLoader.diskCache?.get(key) and context.imageLoader.diskCache?.size work fine after fetching images.

However, every time I restart my app, disk cache gets reset. If I try to call context.imageLoader.diskCache?.size when the app loads, it returns 0. Is this expected behavior?

To Reproduce

  1. Create new image loader

    @OptIn(ExperimentalCoilApi::class)
    override fun newImageLoader(): ImageLoader {
    return ImageLoader.Builder(applicationContext)
        .crossfade(true)
        .diskCachePolicy(CachePolicy.ENABLED)
        .diskCache {
            DiskCache.Builder()
                .directory(applicationContext.cacheDir.resolve("image_cache"))
                .build()
        }
        .memoryCachePolicy(CachePolicy.ENABLED)
        .memoryCache {
            MemoryCache.Builder(applicationContext)
                .maxSizePercent(0.25)
                .build()
        }
        .respectCacheHeaders(false)
        .build()
    }
  2. Fetch images and load it into cache

    val request = ImageRequest.Builder(applicationContext)
    .data(imageUrl)
    .diskCacheKey(imageUrl)
    .build()
    val result = applicationContext.imageLoader.execute(request)

    At this point, applicationContext.imageLoader.diskCache?.get(imageUrl) works fine.

  3. On the next app restart, diskCache is reset. For example....

    applicationContext.imageLoader.diskCache?.get(imageUrl) // Returns null
    applicationContext.imageLoader.diskCache?.size // Returns 0

Version Coil 2.1.0

jikyu commented 2 years ago

There's a related question on stack overflow: https://stackoverflow.com/questions/73221013/kotlin-asyncimage-coil-not-caching-images-properly-keeps-reloading-each-time

jikyu commented 2 years ago

Oops I was using applicationContext.cacheDir, should have used more permanent applicationContext.filesDir