androidkotlinandroid-glidecoil

How to preLoad an image format from the cache and get it later by UID from cache using Coil/Glide


That's say I have a data class from the server in the data layer

data class AvatarPreload(
   val base64: String,
   val uid: Long
)

Then I want to save it into my disk/memory, because the View layer shoudn't need to know the base64 and also base64 is too heavy to carry on

// persudo code
val rq = ImageRequest.Builder(context).data(avatarPreload).memoryCacheKey(avatarPreload.uid.toLong()).build()
context.imageLoader.execute(rq)

Then I'll shrink the data class to a smaller one

data class AvatarForView(
    val uid: Long
)

But I don't know how to get the image only by uid, any Glide/Coil solution will be fine

// persudo code, I want to use uid to get the preload image
val rq = ImageRequest.Builder(context).data(avatarForView.uid).build()
context.imageLoader.execute(rq)

Thanks!!!


Solution

  • I found the way to achieve this,

    So first, change the base64 string to bitmap and save it as follow

    val request = ImageRequest.Builder(context)
    .data(bitmap)
    .memoryCacheKey(uid.toString()) 
    .diskCacheKey(uid.toString())
    .build()
    

    Then, trigger the request by set the data function with empty string e.g. data("")

    val request = ImageRequest.Builder(context)
    .data("") // This is the key step
    .memoryCacheKey(uid.toString())
    .diskCacheKey(uid.toString())
    .target(object: Target {
      // do the work here
    })
    

    because by using this method, it cannot trigger .tranformation() effect, so I have edit my bitmap at .target() step