If you’re like most of the other developers who love to write Android application with Kotlin programming language and uses the Coroutines API for blocking and non-blocking calls. Then you’ll love this new library called Coil-kt. The Kotlin Coil is an image loading library for Android backend by Kotlin Coroutines.
Coil-kt library is purely made with Kotlin and using modern libraries like OkHttp, Okio, and AndroidX lifecycles. It has cool extension function for ImageView and optional trailing lambda for request configuration.
Features of Coil library
Coil offers a large number of features some of these are:
- Drawable Transformation: Coil allows us to modify the pixel data of an image before the drawable returned from the request. It comes with four type of transformation blur, circle crop, greyscale, and rounded corners.
- Suspended Method: To get the drawable synchronously use the
Coil
suspended method..get - Disk Caching: Like Picasso and Glide, Coil downloads the image from the given URL, resize it to size and store it to the disk cache. That will increase the disk cache size, but it will increase the processing speed.
- Customization: It provides various customization and configurations like scaling, crossfade, placeholder, resizing, and many more.
- Canceling on-going Request: The image request will be automatically canceled if the associated view is detached. Additionally, each request returns a Request Disposable which can be used to cancel the request.
- Bitmap Pooling: Similar to Glide, Coil supports bitmap pooling. Bitmap pooling is a technique to re-use bitmap objects once they are no longer in use. This can significantly improve memory performance (especially on pre-Oreo devices).
Coil usage in Android
To use the Coil library in your Android application, first of all, add the following dependency inside the build.gradle
file under app directory.
implementation("io.coil-kt:coil:0.7.0")
Finally, press the Sync Now button and wait until Android Studio finishes syncing your dependencies.
Now that everything is good, let’s download some images and show the result inside the image view.
Download Images using the Extension Function
Coil provides load
a cool extension function for ImageView. Here’s what the code look’s like.
val requestDisposable : RequestDisposable = imageView.load("https://i.ytimg.com/vi/8Zmhd8-Xi5E/maxresdefault_live.jpg")
Coil automatically downloads the image from the given URL and set the result at the image view. You can cancel or check if the on-going image downloading request is completed or not with the RequestDisposable interface.
By default, every request initializes with the default options but you can customize the request with the trailing lambda params.
imageView.load("https://i.ytimg.com/vi/8Zmhd8-Xi5E/maxresdefault_live.jpg") { loadRequestBuilder : LoadRequestBuilder -> loadRequestBuilder.crossfade(true) loadRequestBuilder.scale(Scale.FIT) loadRequestBuilder.placeholder(R.drawable.my_place_holder) loadRequestBuilder.size(width = 250, height = 300) // and many more request options }
Note: The request will be automatically canceled if the view is detached from window.
Download Images with Custom Target View
Now instead of directly loading the drawable into image view, we’ll load the result into a custom target. This way we’ve access to drawable.
val disposable: RequestDisposable = Coil.load("https://i.ytimg.com/vi/8Zmhd8-Xi5E/maxresdefault_live.jpg") { loadRequestBuilder : LoadRequestBuilder -> loadRequestBuilder.target(object : coil.target.Target { override fun onSuccess(result: Drawable) { super.onSuccess(result) // use the drawable maybe extract color from it etc. imageView.setImageDrawable(result) } override fun onStart(placeholder: Drawable?) { super.onStart(placeholder) } override fun onError(error: Drawable?) { super.onError(error) } }) // other request options }
The onStart
and onError
method are optional.
load method supported data types
You can check out all the supported datatypes by Coil-kt library here on this link.
Add Some Suspension To Image Download
To get the image and suspend the current thread until the operation is complete use the following method.
class MyViewModel : ViewModel() { val coroutineContext = Dispatchers.IO + SupervisorJob() fun downloadImage(url : String) { viewModelScope(coroutineContext) { val drawable = Coil.get(url) { // customize the request options } // send drawable back to activity or fragment } } fun cancelDownloading() { coroutineContext.cancelChildren() } }
The code above is pretty straight-forward. If you’re a little bit familiar with Kotlin Coroutines then you probably heard of ” The suspend method can only be a call from another suspend block“. The Coil.get
method is suspended method that’s why we’re calling this method inside the launch builder. Finally, cancels the on-going request if the result is not required.
Drawable Transformation
The simplest way to apply transformation on drawable with Coil-kt is something like this:
imageView.load("https://i.ytimg.com/vi/8Zmhd8-Xi5E/maxresdefault_live.jpg") { loadRequestBuilder : LoadRequestBuilder -> loadRequestBuilder.transformations( CircleCropTransformation(), BlurTransformation(context = [email protected]), // requires context GrayscaleTransformation() ) }
Coil-kt Image Download Listener
You can add listener to LoadRequestBuilder and listens to event when the image downloading start, successfully loads, request cancelled, and fails to load image.
imageView.load("https://i.ytimg.com/vi/8Zmhd8-Xi5E/maxresdefault_live.jpg") { loadRequestBuilder : LoadRequestBuilder -> loadRequestBuilder.listener(object : Request.Listener { override fun onError(data: Any, throwable: Throwable) { super.onError(data, throwable) throwable.printStackTrace() } override fun onCancel(data: Any) { super.onCancel(data) } override fun onStart(data: Any) { super.onStart(data) } override fun onSuccess(data: Any, source: DataSource) { super.onSuccess(data, source) } }) // other request options }
More References:
Alright, guys, thank you for using your precious time reading this article so far. Hopefully, I’ll write another article on Kotlin Coil with advanced features. Stay tuned! In the meantime, you can subscribe to my website at home page for the upcoming articles. Also, if you like the article don’t forget to hit the ♥️ button.
Thank you for being here and keep reading…
2 Comments
Hi great post!! I am using also Coil and it works great. My question: is there any way to load an Uri directly into a Bitmap, i mean in an static way, with no imageview target?
You can use the GetRequest and cast the result ddrawable into Bitmap.
val imageLoader = Coil.imageLoader(context)
val request = GetRequest.Builder(context)
.load(“your image url”)
.build()
val result = (imageLoader .execute(request) as SuccessResult).drawable
val bitmap = (result as BitmapDrawable).bitmap