Created
December 16, 2020 07:45
-
-
Save janakagamini/fa1a6564a7436b8186ce46bec5464918 to your computer and use it in GitHub Desktop.
Filter a list of invalid image urls using coroutines and Glide
This file contains hidden or 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
/** | |
* 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