Skip to content

扩展图片流水线 ​

Android 开箱即用支持多种图片格式,但也有许多格式并不支持(例如 GIF、SVG、MP4 等)。

幸运的是,ImageLoader 支持可插拔组件,用于添加新的缓存层、新的数据类型、新的获取行为、新的图片编码,或者以其他方式覆盖基础图片加载行为。Coil 的图片流水线由五个主要部分组成,并按以下顺序执行:Interceptors、Mappers、Keyers、Fetchers 和 Decoders。

自定义组件必须在通过其 ComponentRegistry 构建 ImageLoader 时添加到其中:

kotlin
val imageLoader = ImageLoader.Builder(context)
    .components {
        add(CustomCacheInterceptor())
        add(ItemMapper())
        add(HttpUrlKeyer())
        add(CronetFetcher.Factory())
        add(GifDecoder.Factory())
    }
    .build()

Interceptor ​

Interceptor 允许你观察、转换、短路或重试发送给 ImageLoader 图片引擎的请求。例如,你可以像这样添加一个自定义缓存层:

kotlin
class CustomCacheInterceptor(
    private val context: Context,
    private val cache: LruCache<String, Image>,
) : Interceptor {

    override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
        val value = cache.get(chain.request.data.toString())
        if (value != null) {
            return SuccessResult(
                image = value,
                request = chain.request,
                dataSource = DataSource.MEMORY_CACHE,
            )
        }
        return chain.proceed()
    }
}

Interceptor 是一项高级功能,可让你使用自定义逻辑包装 ImageLoader 的图片流水线。其设计在很大程度上借鉴了 OkHttp 的 Interceptor 接口。

欲了解更多信息,请参阅 Interceptor。

Mapper ​

Mapper 允许你添加对自定义数据类型的支持。例如,假设我们从服务器获取到以下模型:

kotlin
data class Item(
    val id: Int,
    val imageUrl: String,
    val price: Int,
    val weight: Double
)

我们可以编写一个自定义 Mapper 将其映射为其 URL,该 URL 稍后将在流水线中进行处理:

kotlin
class ItemMapper : Mapper<Item, String> {
    override fun map(data: Item, options: Options) = data.imageUrl
}

在构建 ImageLoader 时注册它(见上文)之后,我们就可以安全地加载 Item 了:

kotlin
val request = ImageRequest.Builder(context)
    .data(item)
    .target(imageView)
    .build()
imageLoader.enqueue(request)

欲了解更多信息,请参阅 Mapper。

Keyer ​

Keyer 将数据转换为缓存键的一部分。当/如果该请求的输出被写入 MemoryCache 时,该值将用作 MemoryCache.Key.key。

欲了解更多信息,请参阅 Keyer。

Fetcher ​

Fetcher 将数据(例如 URL、URI、File 等)转换为 ImageSource 或 Image。它们通常将输入数据转换为可供 Decoder 使用的格式。可以使用此接口来添加对自定义获取机制(例如 Cronet、自定义 URI Scheme 等)的支持。

欲了解更多信息,请参阅 Fetcher。

注意

如果添加了使用自定义数据类型的 Fetcher,你还需要提供一个自定义 Keyer,以确保使用该类型的请求结果可以被内存缓存。例如,Fetcher.Factory<MyDataType> 需要添加对应的 Keyer<MyDataType>。

Decoder ​

Decoder 读取 ImageSource 并返回 Image。可以使用此接口来添加对自定义文件格式(例如 GIF、SVG、TIFF 等)的支持。

欲了解更多信息,请参阅 Decoder。

自定义 ImageLoader 与 ImageRequest 属性 ​

Coil 支持通过 Extras 向 ImageRequest 和 ImageLoader 附加自定义数据。Extras 是通过 Extras.Key 引用的额外属性映射。

例如,假设我们想要为每个 ImageRequest 支持自定义超时时间。我们可以像这样为其添加自定义扩展函数:

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

fun ImageLoader.Builder.timeout(timeout: Duration) = apply {
    extras[timeoutKey] = timeout
}

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

val Options.timeout: Duration
    get() = getExtra(timeoutKey)

// 注意:Extras.Key 实例应该声明为静态的,因为它们是通过实例相等性进行比较的。
private val timeoutKey = Extras.Key(default = Duration.INFINITE)

然后,我们可以在注册到 ImageLoader 中的自定义 Interceptor 内部读取该属性:

kotlin
class TimeoutInterceptor : Interceptor {
    override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
        val timeout = chain.request.timeout
        if (timeout.isFinite()) {
            return withTimeout(timeout) {
                chain.proceed()
            }
        } else {
            return chain.proceed()
        }
    }
}

最后,我们可以在创建 ImageRequest 时设置该属性:

kotlin
AsyncImage(
    model = ImageRequest.Builder(LocalPlatformContext.current)
        .data("https://example.com/image.jpg")
        .timeout(10.seconds)
        .build(),
    contentDescription = null,
)

此外:

  • 我们可以通过定义的 ImageLoader.Builder.timeout 扩展函数来设置默认超时时间。
  • 我们可以通过定义的 Options.timeout 扩展函数在 Mapper、Fetcher 和 Decoder 内部读取超时时间。

Coil 自身也使用了这种模式,用于在 coil-gif 以及其他扩展库中为 GIF 支持自定义请求属性。

链式调用组件 ​

Coil 图片加载器组件的一个实用特性是它们可以在内部进行链式调用。例如,假设你需要执行网络请求来获取要加载的图片 URL。

首先,让我们创建一个仅由我们的 Fetcher 处理的自定义数据类型:

kotlin
data class PartialUrl(
    val baseUrl: String,
)

然后,创建我们的自定义 Fetcher,用于获取图片 URL 并委托给内部的网络 Fetcher:

kotlin
class PartialUrlFetcher(
    private val callFactory: Call.Factory,
    private val partialUrl: PartialUrl,
    private val options: Options,
    private val imageLoader: ImageLoader,
) : Fetcher {

    override suspend fun fetch(): FetchResult? {
        val request = Request.Builder()
            .url(partialUrl.baseUrl)
            .build()
        val response = callFactory.newCall(request).await()

        // 读取图片 URL。
        val imageUrl: String = readImageUrl(response.body)

        // 这将委托给内部的网络 Fetcher。
        val data = imageLoader.components.map(imageUrl, options)
        val output = imageLoader.components.newFetcher(data, options, imageLoader)
        val (fetcher) = checkNotNull(output) { "no supported fetcher" }
        return fetcher.fetch()
    }

    class Factory(
        private val callFactory: Call.Factory = OkHttpClient(),
    ) : Fetcher.Factory<PartialUrl> {
        override fun create(data: PartialUrl, options: Options, imageLoader: ImageLoader): Fetcher {
            return PartialUrlFetcher(callFactory, data, options, imageLoader)
        }
    }
}

最后,我们所需要做的就是在 ComponentRegistry 中注册该 Fetcher,并将 PartialUrl 作为我们的 model/data 传入:

kotlin
AsyncImage(
    model = PartialUrl("https://example.com/image.jpg"),
    contentDescription = null,
)

此模式同样可以应用于 Mapper、Keyer 和 Decoder。