Skip to content

Commit

Permalink
Add cache support in SeedColorExtractor
Browse files Browse the repository at this point in the history
  • Loading branch information
msasikanth committed Oct 1, 2024
1 parent d8bf1e0 commit 319a9f4
Showing 1 changed file with 17 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package dev.sasikanth.rss.reader.ui

import androidx.collection.LruCache
import androidx.collection.lruCache
import androidx.compose.ui.graphics.ImageBitmap
import coil3.ImageLoader
import coil3.PlatformContext
Expand All @@ -33,10 +35,15 @@ class SeedColorExtractor(
private val imageLoader: Lazy<ImageLoader>,
private val platformContext: Lazy<PlatformContext>,
) {
private val lruCache: LruCache<String, Int> = lruCache(maxSize = 100)

@OptIn(ExperimentalCoilApi::class)
suspend fun calculateSeedColor(url: String?): Int? {
if (url.isNullOrBlank()) return null

val cache = lruCache[url]
if (cache != null) return cache

val bitmap: ImageBitmap? = suspendCancellableCoroutine { cont ->
val request =
ImageRequest.Builder(platformContext.value)
Expand All @@ -53,7 +60,16 @@ class SeedColorExtractor(
imageLoader.value.enqueue(request)
}

return bitmap?.seedColor()
return bitmap?.seedColor().also { seedColor ->
if (seedColor != null) {
lruCache.put(url, seedColor)
}
}
}

fun cached(url: String?): Int? {
if (url.isNullOrBlank()) return null
return lruCache[url]
}

private fun ImageBitmap.seedColor(): Int {
Expand Down

0 comments on commit 319a9f4

Please sign in to comment.