Skip to content

Instantly share code, notes, and snippets.

@kasem-sm
Created February 6, 2022 15:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kasem-sm/2801c0c2b2472b6765243ac9b39f7b3b to your computer and use it in GitHub Desktop.
Save kasem-sm/2801c0c2b2472b6765243ac9b39f7b3b to your computer and use it in GitHub Desktop.
Small workaround to show thumbnail before loading actual image with Coil.
var isOriginalImageLoaded = false
// Thumbnail Request
val thumbRequest = ImageRequest.Builder(ctx)
.data(thumbUrl)
.target(
onSuccess = { result ->
// If highRes image is not loaded yet,
// show the thumbnail
if (!isOriginalImageLoaded) {
binding.headerImage.setImageDrawable(result)
}
}
)
.build()
imageLoader.enqueue(thumbRequest)
val highResRequest = ImageRequest.Builder(ctx)
.data(highResUrl)
.target(
onSuccess = { result ->
isOriginalImageLoaded = true
binding.headerImage.setImageDrawable(result)
},
onError = { onFailed() }
)
.build()
imageLoader.enqueue(highResRequest)
@0n4li
Copy link

0n4li commented Feb 21, 2022

Made some modifications using an Extension Function

fun ImageView.loadWithQuality(
    highQuality: String,
    lowQuality: String,
    placeholderRes: Int? = null,
    errorRes: Int? = null
) {

    placeholderRes?.let {
        setImageResource(placeholderRes)
    }

    var isHighQualityLoaded = false

    class CallbackImageViewTarget(val callback: () -> Boolean) : ImageViewTarget(this) {
        override fun onSuccess(result: Drawable) {
            if (callback()) {
                super.onSuccess(result)
            }
        }
    }

    val lowQualityRequest = ImageRequest.Builder(context).apply {
        data(lowQuality)
        target(CallbackImageViewTarget(
            callback = {
                return@CallbackImageViewTarget !isHighQualityLoaded
            }
        ))
    }.build()

    val lowQualityLoader = context.imageLoader.enqueue(lowQualityRequest)

    val highQualityRequest = ImageRequest.Builder(context).apply {
        data(highQuality)
        errorRes?.let { error(errorRes) }
        target(CallbackImageViewTarget(
            callback = {
                isHighQualityLoaded = true
                if (!lowQualityLoader.isDisposed) {
                    lowQualityLoader.dispose()
                }
                return@CallbackImageViewTarget true
            }
        ))
    }.build()

    context.imageLoader.enqueue(highQualityRequest)

}

@kasem-sm
Copy link
Author

Thanks for checking and improving it :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment