[Android/Jetpack Compose] Coil ~cache network images for either device or memory~

Android

What is Coil?

Coil is an image loading library for Android backed Kotlin Coroutines

Detail information is here.

You can load images from your local device or network image. Futhermore,What you can get benefits to use is caching. Coil gives us caching images functionarities for your application.

How to use

At first, you have to create MyApplication class which inherites Application class like the below.

@HiltAndroidApp
class MyApplication : Application()

The main reason to extends Application class is implementing new Imageloader.

Like this.

@HiltAndroidApp
class MyApplication : Application(), ImageLoaderFactory {
    var shouldRefreshCache = false

    override fun newImageLoader(): ImageLoader {
    // ・・・ continue

In your newImageLoader, you can implement new features about how to cache. In this article, I'll introduce you guys some basic useage. Entire code of MyApplication is the below.

class MyApplication : Application(), ImageLoaderFactory {
    var shouldRefreshCache = false

    override fun newImageLoader(): ImageLoader {
        return ImageLoader(this)
            .newBuilder()
            .memoryCachePolicy(CachePolicy.ENABLED) // ※1
            .memoryCache {
                MemoryCache.Builder(this)
                    .maxSizePercent(0.1) // ※2
                    .strongReferencesEnabled(true) // ※3
                    .build()
            }
            .diskCachePolicy(CachePolicy.ENABLED) // ※4
            .diskCache {
                DiskCache.Builder()
                    .maxSizePercent(0.03)
                    .directory(cacheDir) // ※5
                    .build()
            }
            .logger(DebugLogger()) // ※6
            .build()
    }
}
  • ※1: You can choose whether memory cache is enable or not. If the memory cache is active loading images is faster than that of disk. But of cource it consume memory capability.

  • ※2: You can deceide how much limit cache uses the memory. In this case, less than 0.1% of memory will be use as caching. If you want to decide memory limit as directly you can use maxSizeBytes'()

  • ※3: If you don't want to dispose cache images unexpectedly you sould use this option.

  • ※4: As memoryCachePolicy, you can decide whethre disk cache is enable or not. But you might use this libraly because you want to cache images you would be active of this option.

  • ※5 : You can decide where to locate the cahing images, if you don't have any extra thoughts, directory(cacheDir) will be best location to cache.

  • ※6 : It's very useful to check logs in your terminal. I recommend to use logger as default.

コメント

タイトルとURLをコピーしました