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)
相关推荐
胖大师9 小时前
Android Audio-FW
android
kayyoo11 小时前
CoordinatorLayout解析(二): 结合CollapsingToolbarLayout实现Toolbar折叠效果
android
数据知道13 小时前
移动端渗透测试流程:Android APK 逆向与动态调试
android·web安全·网络安全
我命由我1234514 小时前
人脸识别 - 勒克斯(光线照射到物体表面上的明亮程度)
android·java·学习·java-ee·人脸识别·学习方法·android runtime
聚美智数15 小时前
护照OCR识别-护照图像识别-护照OCR文字识别-护照识别OCR-护照信息识别-护照OCR
android·ocr
码农coding16 小时前
android12 点击桌面应用图标启动Activity流程
android
johnsong17 小时前
深度拆解:150M循环模型如何用循环推理击败大Transformer
android·深度学习·transformer
JMchen12317 小时前
Jetpack 内核实战(九):实战(上)——记事本首页列表 + 搜索功能开发
kotlin·android 实战·记事本 app 开发·recyclerview 优化·jetpack 综合实战
CedarQR18 小时前
云卓 G20 遥控器 Android 开发实录:从 USB 设备到读取摇杆/按键通道值
android·linux·无人机
pengyu18 小时前
【Kotlin 协程修仙录 · 炼虚境 · 初阶】 | 虚空造物:Channel 基础与协程间通信的管道艺术
android·前端·kotlin