Added avatar caching

This commit is contained in:
Abdelilah El Aissaoui 2021-12-02 01:50:59 +01:00
parent a948e2da06
commit b518c5007e
4 changed files with 43 additions and 15 deletions

View File

@ -0,0 +1,6 @@
package app.images
interface ImagesCache {
fun getCachedObject(urlSource: String): ByteArray?
fun cacheImage(urlSource: String, image: ByteArray)
}

View File

@ -0,0 +1,13 @@
package app.images
object InMemoryImagesCache : ImagesCache {
private val cachedImages = hashMapOf<String, ByteArray>()
override fun getCachedObject(urlSource: String): ByteArray? {
return cachedImages[urlSource]
}
override fun cacheImage(urlSource: String, image: ByteArray) {
cachedImages[urlSource] = image
}
}

View File

@ -32,6 +32,8 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.toComposeImageBitmap
import app.ui.components.ScrollableLazyColumn
import app.git.GitManager
import app.images.ImagesCache
import app.images.InMemoryImagesCache
import app.theme.headerText
import org.eclipse.jgit.lib.PersonIdent
import org.jetbrains.skia.Image.Companion.makeFromEncoded
@ -171,26 +173,32 @@ suspend fun loadImage(link: String): ByteArray = withContext(Dispatchers.IO) {
}
@Composable
fun rememberNetworkImage(url: String): ImageBitmap {
fun rememberNetworkImage(url: String, cache: ImagesCache = InMemoryImagesCache): ImageBitmap {
val cachedImage = cache.getCachedObject(url)
var image by remember(url) {
mutableStateOf<ImageBitmap>(
if(cachedImage != null)
mutableStateOf(makeFromEncoded(cachedImage).toComposeImageBitmap())
else
mutableStateOf(
useResource("image.jpg") {
makeFromEncoded(it.toByteArray()).toComposeImageBitmap()
}
)
}
if(cachedImage == null) {
LaunchedEffect(url) {
try {
loadImage(url).let {
image = makeFromEncoded(it).toComposeImageBitmap()
cache.cacheImage(url, it)
}
} catch (ex: Exception) {
println("Avatar loading failed: ${ex.message}")
}
}
}
return image
}

View File

@ -1,4 +1,5 @@
@file:OptIn(ExperimentalComposeUiApi::class)
@file:Suppress("UNUSED_PARAMETER")
package app.ui
@ -493,7 +494,7 @@ fun CommitNode(
.border(2.dp, color, shape = CircleShape)
.clip(CircleShape)
) {
val url = "https://www.gravatar.com/avatar/${plotCommit.authorIdent.emailAddress.md5}"
val url = "https://www.gravatar.com/avatar/${plotCommit.authorIdent.emailAddress.md5}?s=60"
Image(
bitmap = rememberNetworkImage(url),
modifier = Modifier