Skip to content

Instantly share code, notes, and snippets.

@esabook
Created December 21, 2021 09:37
Show Gist options
  • Save esabook/050b353e6610353812f18b296f2a232c to your computer and use it in GitHub Desktop.
Save esabook/050b353e6610353812f18b296f2a232c to your computer and use it in GitHub Desktop.
Imageloader for glide, auto stop/dispose when View.onDetach()
fun ImageView.loadImageWithGlide(
imgObj: Any?,
cacheMode: DiskCacheStrategy = DiskCacheStrategy.AUTOMATIC,
onFail: (() -> Unit?)? = null,
onSuccess: (() -> Unit?)? = null,
) {
try {
Glide.with(this)
.load(imgObj)
.placeholder(this.drawable)
.error(this.drawable)
.diskCacheStrategy(cacheMode)
.addListener(object : RequestListener<Drawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
onFail?.invoke()
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
onSuccess?.invoke()
return false
}
})
.into(this)
.clearOnDetach()
} catch (e: Exception) {
Timber.w(e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment