Home > front end >  Android Coil custom extension function not working
Android Coil custom extension function not working

Time:06-19

Objective: load the image only if present in the coil cache. Using the extension function imageView.load(url) {} --you cannot configure the request-- (update: wrong assumption), 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?

CodePudding user response:

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).

  • Related