I wanted to add a disk cache feature to Coil image loading to speed up image loading by using cached images. However, after implementing the cache feature, image loading has become significantly slower.
Below is my code with the disk cache feature:
private fun newDiskCache(): DiskCache {
return DiskCache.Builder().directory(FileSystem.SYSTEM_TEMPORARY_DIRECTORY / "image_cache")
.maxSizeBytes(512 * 1024 * 1000)
.build()
}
private fun newMemoryCache(): MemoryCache {
return MemoryCache.Builder()
.maxSizePercent(context = PlatformContext.INSTANCE, percent = 0.3)
.strongReferencesEnabled(enable = true)
.weakReferencesEnabled(enable = true)
.build()
}
private fun getAsyncImageLoader(): ImageLoader {
return ImageLoader.Builder(PlatformContext.INSTANCE)
.memoryCachePolicy(CachePolicy.ENABLED)
.diskCachePolicy(CachePolicy.ENABLED)
.memoryCache(newMemoryCache())
.diskCache(newDiskCache())
.logger(DebugLogger())
.build()
}
@Composable
fun UserAvatar(
avatar: CommunityImage,
contentScale: ContentScale = ContentScale.Fit,
modifier: Modifier = Modifier,
) {
AsyncImage(
model = ImageRequest.Builder(PlatformContext.INSTANCE)
.data(data)
.error { MR.images.ic_avatar_preview.image.toBitmap().asImage() }
.memoryCacheKey(key = data.toString())
.diskCacheKey(key = data.toString())
.crossfade(enable = true)
.build(),
contentDescription = null,
modifier = modifier,
imageLoader = getAsyncImageLoader(),
contentScale = contentScale,
)
}
This is the old code, which loads images faster but always fetches them from the network. I wanted to avoid this and load images from the cache if they had been previously loaded.
@Composable
fun UserAvatar(
avatar: CommunityImage,
contentScale: ContentScale = ContentScale.Fit,
modifier: Modifier = Modifier,
) {
AsyncImage(
model = ImageRequest.Builder(PlatformContext.INSTANCE)
.data(data)
.error { MR.images.ic_avatar_preview.image.toBitmap().asImage() }
.crossfade(enable = true)
.build(),
contentDescription = null,
modifier = modifier,
imageLoader = ImageLoader.Builder(PlatformContext.INSTANCE).build(),
contentScale = contentScale,
)
}
I tried changing maxSizeBytes
and maxSizePercent
in various ways, but I didn’t see any improvements.