Created
December 21, 2021 09:37
-
-
Save esabook/050b353e6610353812f18b296f2a232c to your computer and use it in GitHub Desktop.
Imageloader for glide, auto stop/dispose when View.onDetach()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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