Caching images in android is key for performance issues. We can write our own AsyncTask to manage it well or use Picasso with one-line of code:
1 |
Picasso.with(context).load(path).into(imageView); |
When we develop our app in Kotlin we can make it smarter using Extension Properties.
Let’s create a new file inside our utils package, call it picasso.kt and fill it with simple code below:
1 2 |
public val Context.picasso: Picasso get() = Picasso.with(this) |
While this corresponds to the receiver object we can invoke following code on any Context:
1 |
picasso.load(path).into(imageView) |
We can go further and extend ImageView class like:
1 2 3 |
public fun ImageView.load(path: String, request: (RequestCreator) -> RequestCreator) { request(getContext().picasso.load(path)).into(this) } |
Now call might look really nice:
1 |
imageView.load(path) { request -> request.centerCrop() } |