Skip to content

Instantly share code, notes, and snippets.

@CristianMG
Created September 4, 2019 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CristianMG/d0b41692f240ef4c56fa24285d43b817 to your computer and use it in GitHub Desktop.
Save CristianMG/d0b41692f240ef4c56fa24285d43b817 to your computer and use it in GitHub Desktop.
Loaders
inner class FromResource private constructor() {
constructor(init: FromResource.() -> Unit) : this() {
init()
}
@DrawableRes
var resource: Int? = null
fun resource(init: () -> Int) {
resource = init()
}
fun load(imageView: ImageView) {
if (resource == null) {
Timber.e("The res cannot be 0")
return
}
resource?.let {
imageView.setTag(IMAGE_LOADER_TAG, StateLoaded.LoadedFromResource(it, false))
imageView.setImageResource(it)
}
}
fun loadBackground(view: View) {
if (resource == null) {
Timber.e("The res cannot be 0")
return
}
resource?.let {
view.setTag(IMAGE_LOADER_BACKGROUND_TAG, StateLoaded.LoadedFromResource(it, true))
view.setBackgroundResource(it)
}
}
}
inner class FromNetwork private constructor() {
constructor(init: FromNetwork.() -> Unit) : this() {
init()
}
private var url: String = ""
private var placeHolder: Int? = null
private var errorPlaceHolder: Int? = null
private var success: ((drawable: Drawable) -> Unit)? = null
private var error: ((exception: GlideException?) -> Unit)? = null
fun url(init: () -> String) {
url = init()
}
fun error(init: () -> Int) {
errorPlaceHolder = init()
}
fun placeholder(init: () -> Int) {
placeHolder = init()
}
fun successCallback(init: () -> ((drawable: Drawable) -> Unit)) = apply { this.success = init() }
fun errorCallback(init: () -> ((exception: GlideException?) -> Unit)) = apply { this.error = init() }
fun load(imageView: ImageView) {
Timber.d("Loading image $url in ${imageView.id}")
val options = RequestOptions()
placeHolder?.let { options.placeholder(it) }
errorPlaceHolder?.let { options.error(it) }
placeHolder?.let { options.placeholder(it) }
networkLoader.load(options, url, success, error, imageView)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment