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 对比
| 特性 | Glide | Coil |
|---|---|---|
| 缓存层级 | 三级(Active + Memory + Disk) | 二级(Memory + Disk) |
| 异步模型 | 线程池 | 协程 |
| Compose | 需 accompanist | 原生 AsyncImage |
| 生命周期 | 空 Fragment | Lifecycle 直接绑定 |
| 扩展性 | Transform + Module | Interceptor Chain |
| 社区生态 | 更成熟,文档更丰富 | 快速增长,现代化 |
选型建议
- 新 Kotlin/Compose 项目 → Coil(API 更 Kotlin-friendly)
- Java 项目 / 复杂需求 → Glide(生态成熟,GIF/视频帧支持更好)
常见面试问题
Q1: Coil 的协程优势体现在哪里?
答案:
- 结构化并发:图片请求自动绑定 CoroutineScope,页面销毁时自动取消
- 挂起函数:
imageLoader.execute(request)返回ImageResult,可以直接在协程中使用 - Flow 集成:配合
StateFlow实现响应式图片加载状态管理 - 线程切换:协程 Dispatcher 替代线程池,调度更高效
Q2: Coil 的生命周期绑定和 Glide 有什么不同?
答案:
Glide 通过添加空 Fragment 监听生命周期(兼容旧版本 Android)。Coil 直接使用 Jetpack Lifecycle 组件,通过 LifecycleObserver 监听生命周期,不需要额外的 Fragment,更加轻量和直接。