Coil picture frame

Coil is a Kotlin framework recently discovered by the Kotlin project, which is a good part of the project in conjunction with the coroutine and Okhttp3, without being too intrusive

Application method of Coil

ImageView.load(data Any)

It’s as simple as that. If you’re new to the framework, you can use it, or you can use Apply to extend and modify your images

Analysis of Coil source code

@JvmSynthetic inline fun ImageView.loadAny( data: Any? , imageLoader: ImageLoader = context.imageLoader, builder: ImageRequest.Builder.() -> Unit = {} ): Disposable { val request = ImageRequest.Builder(context) .data(data) .target(this) .apply(builder) .build() return imageLoader.enqueue(request) }Copy the code

By observation, we find that all supported load methods will end up in loadAny method by adding load data through ImageRequest constructor, traget which view is loaded, whether apply is extended, and finally call build method to obtain ImageRequest object. Request through the imageLoader method

Inside imageRequest is some configuration information

ImageLoader uses the Coil. ImageLoader (this) methodAnd then in Coil newImageLoader()

Usually we use the ImageLoader(context) with nothing configured, then call the build method in the associated object in the ImageLoader, create the ImageLoader and then use a lot of coroutine methods in the request. If you are interested, read it for yourself

Coil extension

Mbinding.testcoiliv.load (" URL "){crossfade(true) // fade out placeholder(r.rawable.tab_shop_selected) // placeholder You can make a quick change in your picture, or you can make a quick change in your picture, or you can make a quick change in your picture.Copy the code

Easiest way to use

        val listener: ImageRequest.Listener =
            object : ImageRequest.Listener {
                override fun onStart(imageRequest: ImageRequest) {

                }
                override fun onCancel(imageRequest: ImageRequest) {

                }
                override fun onError(
                    imageRequest: ImageRequest,
                    throwable: Throwable
                ) {
                }

                override fun onSuccess(
                    imageRequest: ImageRequest,
                    metadata: ImageResult.Metadata
                ) {
                }
            }
        val request = ImageRequest.Builder(this)
            .data("url")
            .target {
                mBinding.testCoilIv.setImageDrawable(it)
            }
            .listener(listener)
            .build()

        imageLoader.enqueue(request)
Copy the code

The second way is actually to add some configuration items, the code is more intuitive