2

I want to load the image on the spash screen so that I can set the request result to the background on other screens using the coil, but I have not been able to fully realize this in the coil. How can I save the result of my coil request to Cahce and use this result on other screens?

Splash Screen

val imageLoader = ImageLoader.Builder(this)
        .memoryCache {
            MemoryCache.Builder(this)
                .maxSizePercent(0.25)
                .strongReferencesEnabled(true)
                .build()
        }
            
            
        .diskCache {
            DiskCache.Builder()
                .directory(this.cacheDir.resolve("image_cache"))
                .maxSizePercent(0.02)
                .build()
        }
        .build()

and I used like this on splash

    val context = LocalContext.current
    val request = ImageRequest.Builder(context)
        .memoryCacheKey(Constants.Cache.BACKGROUND_IMAGE_KEY)
        .data("https://www.example/image1.jpg")
        .target(
            onSuccess = {
                viewModel.skipImageRequest()
            },
            onError = {
                viewModel.skipImageRequest()
            }
        )
        .build()
    imageLoader.enqueue(request)

in another screen that I want to use image

@Composable
fun BackgroundImage(
    model: Any?,
    contentDescription: String? = "",
    modifier: Modifier = Modifier.fillMaxSize(),
    //placeholder: Painter? = painterResource(R.drawable.bg_placeholder),
    error: Painter? = painterResource(R.drawable.bg_placeholder),
    fallback: Painter? = painterResource(R.drawable.bg_placeholder),
    alignment: Alignment = Alignment.Center,
    contentScale: ContentScale = ContentScale.FillBounds
) {
    AsyncImage(
        model = ImageRequest.Builder(LocalContext.current)
            .data("https://www.example/image1.jpg")
            .placeholderMemoryCacheKey(Constants.Cache.BACKGROUND_IMAGE_KEY)
            .build(),
        contentDescription = contentDescription,
        modifier = modifier,
        //placeholder = placeholder,
        error = error,
        fallback = fallback,
        alignment = alignment,
        contentScale = contentScale,
    )
}

There is an always problem the placeholder image is shown in initialize of page I could not construct a structure where the placeholder is not visible while the image is being loaded and the image is read and used directly from the cahce.

I would be very happy if you support

1 Answers1

0

Coil internally uses OkHttp's DiskCache in 1.x version For 2.x they have introduced a disk cache to store your result.

For further information read this

PunK _l_ RuLz
  • 621
  • 6
  • 20