Skip to content

Instantly share code, notes, and snippets.

@janakagamini
Created December 16, 2020 07:45
Show Gist options
  • Save janakagamini/fa1a6564a7436b8186ce46bec5464918 to your computer and use it in GitHub Desktop.
Save janakagamini/fa1a6564a7436b8186ce46bec5464918 to your computer and use it in GitHub Desktop.
Filter a list of invalid image urls using coroutines and Glide
/**
* From the given list of urls, returns a list of urls that were successfully downloaded by Glide
* and cached.
*
* @param imageUrls List of image urls.
* @return
*/
suspend fun Activity.tryImageUrls(imageUrls: List<String>): List<String> {
return imageUrls.map {
try {
tryImageUrl(this, it)
} catch (e: Exception) {
null
}
}.mapNotNull { it }
}
private suspend fun tryImageUrl(activity: Activity, imageUrl: String): String {
val response = CompletableDeferred<String>()
Glide.with(activity)
.asBitmap()
.load(imageUrl)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
response.complete(imageUrl)
}
override fun onLoadCleared(placeholder: Drawable?) {
}
override fun onLoadFailed(errorDrawable: Drawable?) {
super.onLoadFailed(errorDrawable)
response.completeExceptionally(Exception("Url failed."))
}
})
return response.await()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment