Thanks Kotlin for making this utility function soo...
# android
p
Thanks Kotlin for making this utility function soooooo simple ๐Ÿค—๐Ÿ™ƒ๐Ÿ˜‹
Copy code
fun ImageView.loadImage(
        url: String?,
        @DrawableRes placeholder: Int? = null,
        circular: Boolean = false,
        roundedCorners: Int = 0
) {
    Glide.with(context)
            .load(url)
            .apply {
                placeholder?.let { apply(RequestOptions().placeholder(it)) }
                if (circular) {
                    apply(RequestOptions.circleCropTransform())
                } else if (roundedCorners != 0) {
                    apply(RequestOptions.bitmapTransform(RoundedCorners(context.dip(roundedCorners))))
               }
            }
            .into(this)
}
I would love to get any suggestions/improvements to this function.
d
Copy code
fun ImageView.loadImage(
        url: String?,
        @DrawableRes placeholder: Int? = null,
        circular: Boolean = false,
        roundedCorners: Int = 0
) {
    with(Glide.with(context)) {
        load(url)
        placeholder?.let { apply(RequestOptions().placeholder(it)) }
        if (circular) {
            apply(RequestOptions.circleCropTransform())
        } else if (roundedCorners != 0) {
            apply(RequestOptions.bitmapTransform(RoundedCorners(context.dip(roundedCorners))))
        }
        into(this@loadImage)
    }
}
More of an alternative, than an improvement I guess.
p
this@loadImage
though ๐Ÿ˜ฃ
d
Copy code
fun ImageView.loadImage(
        url: String?,
        @DrawableRes placeholder: Int? = null,
        circular: Boolean = false,
        roundedCorners: Int = 0
) {
    with(Glide.with(context)) {
        load(url)
        placeholder?.let { apply(RequestOptions().placeholder(it)) }
        if (circular) {
            apply(RequestOptions.circleCropTransform())
        } else if (roundedCorners != 0) {
            apply(RequestOptions.bitmapTransform(RoundedCorners(context.dip(roundedCorners))))
        }
    }.into(this)
}
๐Ÿ™ƒ 1
๐Ÿ˜‚ 3
๐Ÿ‘ 1
๐Ÿ™‚
k
4 params for one function? Is it not it too much? Generally, I never cross 3 params, ideally go for max 2 params for a clean code
j
More params mean more utility though /s
p
The use of named args with default values makes it cleaner.
d
Might as well make a DSL too.
k
Don't go overboard with DSLs. It takes ages to compile code that is using non trivial DSL parts
So something like 3-4 levels nested makes the compiler extra busy
p
Also, avoid using
Glide.with(context)
directly. If you can, generate
RequestManager
using
Glide.with(this)
in your
Activities
or
Fragments
. This step will help you a lot to reclaim memory when your fragment or activity is out of lifecycle.