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)
相关推荐
Mr_万能胶1 小时前
官方发布,不烧心的 AOSP 编译提速技巧
android·ci/cd·架构
booboosui1 小时前
安卓 8.1 也能装了:代价是一条黄字和两个静默 bug
android
Ehtan_Zheng4 小时前
Jetpack AppState Transform:让 Compose 的响应式状态走出 UI 层
android
OriginCoding4 小时前
一个 JDK 跑起六个分布式挑战:Kotlin 版 Gossip Glomers(一)
分布式·kotlin
yyuuuzz6 小时前
nginx 502 排查,先看上游超时那一行
android·java·运维·nginx·502
恋猫de小郭10 小时前
Flutter 3.50.0 Release 的第一个崩溃,修好了,还没 hotfix
android·前端·flutter
alexhilton20 小时前
MVI 让屏幕一次只有一个状态
android·kotlin·android jetpack
二流小码农1 天前
鸿蒙开发:证书只能创建3个,第4个应用怎么办
android·ios·harmonyos
阿杰m1 天前
Android源码第十七章:PowerManager 与后台任务——锁屏后怎么跑?
android
JMchen1231 天前
【Android 性能优化实战 60 讲】10 Jetpack App Startup 内核魔改:手写异步懒加载启动框架,根治串行初始化耗时
android·性能优化·源码分析·启动优化·kotlin协程·app startup