Android Coil 3 extend ImageRequest‘s custom method/function,Kotlin

Android Coil 3 extend ImageRequest's custom method/function,Kotlin

为Android Coil3图像加载库扩展自定义超时功能。通过创建MyCoilMgr类,使用companion object定义timeout扩展函数和属性,并实现TimeoutInterceptor拦截器来监控请求耗时。拦截器使用withTimeoutOrNull协程函数处理超时逻辑,记录请求耗时或超时情况。最后展示了使用方式:通过ImageRequest.Builder.timeout()设置超时时间,并用MyCoilMgr实例执行请求。该方案为Coil3提供了灵活的超时控制能力。

Kotlin 复制代码
class MyCoilMgr {
    companion object {
     
        private val timeoutKey = Extras.Key(default = Long.MAX_VALUE)

        fun ImageRequest.Builder.timeout(timeout: Long) = apply {
            extras[timeoutKey] = timeout
        }

        val ImageRequest.timeout: Long
            get() = getExtra(timeoutKey)


        ...
    }

    
    fun init(ctx: Context): ImageLoader {

        //初始化加载器。
        mImageLoader = ImageLoader.Builder(ctx)
            ...
            .components {
                add(TimeoutInterceptor())
            }.build()

        return mImageLoader
    }
}
Kotlin 复制代码
import android.util.Log
import coil3.intercept.Interceptor
import coil3.request.ImageResult
import com.ppdemo.coil.MyCoilMgr.Companion.timeout
import kotlinx.coroutines.withTimeoutOrNull

class TimeoutInterceptor : Interceptor {
    companion object {
        const val TAG = "fly/TimeoutInterceptor"
    }

    var startTime = 0L
    var timeCost = 0L
    lateinit var result: ImageResult

    override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
        val timeout = chain.request.timeout

        val exe = withTimeoutOrNull(timeout, {
            startTime = System.currentTimeMillis()
            result = chain.proceed()
            timeCost = System.currentTimeMillis() - startTime
        })

        if (exe == null) {
            Log.e(TAG, "timeout! $timeout ms , request=${chain.request.data}")
        } else {
            Log.d(TAG, "time cost = $timeCost ms , request=${chain.request.data}")
        }

        return result
    }
}

so, we can use it in ImageRequest, for example:

Kotlin 复制代码
        val req = ImageRequest.Builder(this)
            ....
            .timeout(1000)
            .build()
        MyCoilMgr.INSTANCE.enqueue(req)
相关推荐
杉氧14 小时前
100% Kotlin:基于 KMP + Compose Multiplatform 的全栈架构实战(Clean Architecture + MVI)
android·架构
小仙女喂得猪14 小时前
AI 写 Android 代码老翻车?我把移动端的 Harness 系统开源了
android·github·ai编程
杉氧14 小时前
第一篇:从一个 Dagger 报错开始:手把手带你搭建 Hilt 依赖注入的护城河
android·架构
咋吃都不胖lyh14 小时前
短期记忆和长期记忆都存 MySQL
android·java·开发语言
杊页16 小时前
系列三:组件化与模块化进阶 | 第8篇 组件化与模块化核心实战区别:大型项目架构的必由之路
android·android jetpack
曲幽17 小时前
旧手机别扔!用 Termux 搭个私人云盘,比网盘香多了
android·termux·alist·filebrowser
唐青枫18 小时前
Kotlin also 详解:附加操作、链式调试与实战示例
kotlin
Kapaseker19 小时前
Android 开发来看看 Kotlin 2.4.0 更新了个啥
android·kotlin
前端与小赵19 小时前
快速生成安卓证书并打包生成安卓apk(保姆教程)
android·前端
吃螺丝粉19 小时前
MySQL 5.7 到 9.7.0 LTS 升级核心指南
android