跳到主要内容

Coil 原理

问题

Coil 的设计理念是什么?和 Glide 有什么不同?

答案

Coil 的特点

Coil(Coroutine Image Loader)是 Kotlin First 的图片加载库:

  • 协程驱动:基于 Kotlin 协程,天然支持 suspend 和结构化并发
  • Compose 集成AsyncImage 开箱即用
  • 拦截器模式:类似 OkHttp 的 Interceptor Chain
  • 体积小:约 250KB(Glide ~440KB)

基本使用

// View 系统
imageView.load("https://example.com/image.jpg") {
crossfade(true)
placeholder(R.drawable.placeholder)
error(R.drawable.error)
transformations(CircleCropTransformation())
}

// Jetpack Compose
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data("https://example.com/image.jpg")
.crossfade(true)
.build(),
contentDescription = "Photo",
modifier = Modifier.size(200.dp),
contentScale = ContentScale.Crop
)

Coil 架构

自定义拦截器

class LoggingInterceptor : Interceptor {
override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
val start = System.currentTimeMillis()
val result = chain.proceed(chain.request)
val duration = System.currentTimeMillis() - start
Log.d("Coil", "Loaded ${chain.request.data} in ${duration}ms")
return result
}
}

// 注册
val imageLoader = ImageLoader.Builder(context)
.components {
add(LoggingInterceptor())
}
.build()

Coil vs Glide 对比

特性GlideCoil
缓存层级三级(Active + Memory + Disk)二级(Memory + Disk)
异步模型线程池协程
Compose需 accompanist原生 AsyncImage
生命周期空 FragmentLifecycle 直接绑定
扩展性Transform + ModuleInterceptor Chain
社区生态更成熟,文档更丰富快速增长,现代化
选型建议
  • 新 Kotlin/Compose 项目 → Coil(API 更 Kotlin-friendly)
  • Java 项目 / 复杂需求 → Glide(生态成熟,GIF/视频帧支持更好)

常见面试问题

Q1: Coil 的协程优势体现在哪里?

答案

  1. 结构化并发:图片请求自动绑定 CoroutineScope,页面销毁时自动取消
  2. 挂起函数imageLoader.execute(request) 返回 ImageResult,可以直接在协程中使用
  3. Flow 集成:配合 StateFlow 实现响应式图片加载状态管理
  4. 线程切换:协程 Dispatcher 替代线程池,调度更高效

Q2: Coil 的生命周期绑定和 Glide 有什么不同?

答案

Glide 通过添加空 Fragment 监听生命周期(兼容旧版本 Android)。Coil 直接使用 Jetpack Lifecycle 组件,通过 LifecycleObserver 监听生命周期,不需要额外的 Fragment,更加轻量和直接。

相关链接