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)
相关推荐
星河漫步Lu1 小时前
QT6中五步完成Android的环境配置
android·qt
UXbot2 小时前
AI 原型工具对比(2026):从文字描述到完整 App 界面的 5 款主流平台评测
android·前端·ios·交互·软件构建
Empty-Filled2 小时前
Prompt改版后怎么回归:一套测试集和评分方法
回归·kotlin·prompt
三少爷的鞋3 小时前
Android Clean Architecture 中 Use Case 只能有一个方法吗?
android
思麟呀3 小时前
MySQL复合查询与内外连接
android·数据库·mysql
程序员陆业聪11 小时前
两次Flutter全屏白踩坑复盘:Layout的静默失败,以及AI结对编程的认知盲区
android
程序员陆业聪13 小时前
Compose Strong Skipping Mode 的真相:它并不会让你的类型变 Stable
android
阿巴斯甜16 小时前
launch 和 async 内部都是串行,为什么还能实现并发?
kotlin
shaoming377617 小时前
浏览器动作开发:地址栏图标点击事件、弹出页面设计
android·mysql·adb