Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Android Coil custom extension function not working

Objective: load the image only if present in the coil cache.
Using the extension function imageView.load(url) {}
you cannot configure the request, so you must write this whole code instead (docs):

            val imageLoader = holder.myImageView.context.imageLoader
            val request = ImageRequest.Builder(holder.myImageView.context)
                .data(url)
                .target(holder.myImageView)
                .networkCachePolicy(CachePolicy.DISABLED)
                .diskCachePolicy(CachePolicy.ENABLED)
                .memoryCachePolicy(CachePolicy.ENABLED)
                .build()
            imageLoader.enqueue(request)

This code works so I’m trying to move this to an own extension function ImageView.loadFromCache() like this:

fun ImageView.loadFromCache(
    data: Any?
): Disposable {

    val noCacheBuilder : ImageRequest.Builder.() -> Unit = {
        ImageRequest.Builder(context.applicationContext)
            .networkCachePolicy(CachePolicy.DISABLED)
            .diskCachePolicy(CachePolicy.ENABLED)
            .memoryCachePolicy(CachePolicy.ENABLED)
    }
    return load(data, builder = noCacheBuilder)
}

Now I can call holder.myImageView.loadFromCache(url) which executes without error but here my policies are completely ignored, any idea why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try replacing:

    val noCacheBuilder : ImageRequest.Builder.() -> Unit = {
        ImageRequest.Builder(context.applicationContext)
            .networkCachePolicy(CachePolicy.DISABLED)
            .diskCachePolicy(CachePolicy.ENABLED)
            .memoryCachePolicy(CachePolicy.ENABLED)
    }

with:

    val noCacheBuilder : ImageRequest.Builder.() -> Unit = {
        this.networkCachePolicy(CachePolicy.DISABLED)
            .diskCachePolicy(CachePolicy.ENABLED)
            .memoryCachePolicy(CachePolicy.ENABLED)
    }

The receiver of that lambda expression is an ImageRequest.Builder. Your current code is ignoring it and is creating a new one, which then never leaves that lambda expression (as it returns Unit).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading