gpt4 book ai didi

android - 线圈图像缓存不适用于 Jetpack Compose

转载 作者:行者123 更新时间:2023-12-05 04:26:42 27 4
gpt4 key购买 nike

我正在使用 coil(version 2.1.0)从 URL 加载图像。当有网络连接时,图像加载正常。但是,当没有网络连接时,图像不会像我预期的那样从缓存中提取出来。这是我的一段代码。

class App : Application(), ImageLoaderFactory {

override fun newImageLoader(): ImageLoader {
return ImageLoader.Builder(this)
.memoryCache {
MemoryCache.Builder(this)
.maxSizePercent(0.25)
.build()
}
.diskCache {
DiskCache.Builder()
.directory(cacheDir.resolve("image_cache"))
.maxSizeBytes(5 * 1024 * 1024)
.build()
}
.build()
}
}

在撰写中:

                val context = LocalContext.current
val placeholderImage = R.drawable.ic_placeholder

val imageRequest = ImageRequest.Builder(context)
.data(imageUrl)
.memoryCacheKey(imageUrl)
.diskCacheKey(imageUrl)
.placeholder(placeholderImage)
.error(placeholderImage)
.fallback(placeholderImage)
.diskCachePolicy(CachePolicy.ENABLED)
.memoryCachePolicy(CachePolicy.ENABLED)
.transformations(CircleCropTransformation())
.build()

AsyncImage(
model = imageRequest,
modifier = Modifier.size(64.dp),
contentDescription = null,
imageLoader = context.imageLoader
)

当设备处于离线状态时,它只会加载占位符图像,而不是像预期的那样从缓存中加载图像。我在这里缺少什么?

最佳答案

coil 将根据 http header 中的 Cache-Control 字段来决定是否需要磁盘缓存。

这里是coil 2.0.0的更新日志

  • New: Introduce a public DiskCache API.
    • Use ImageLoader.Builder.diskCache and DiskCache.Builder to configure the disk cache.
    • You should not use OkHttp's Cache with Coil 2.0. See here for moreinfo.
    • Cache-Control and other cache headers are still supported - except Vary headers, as the cache only checks that the URLs match.Additionally, only responses with a response code in the range[200..300) are cached.
    • Existing disk caches will be cleared when upgrading to 2.0.

如果需要强制缓存,参见https://coil-kt.github.io/coil/recipes/#headers .而且我认为最好使用 addHeader 来避免丢弃其他 http header 字段。

关于android - 线圈图像缓存不适用于 Jetpack Compose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72981927/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com