Home > Software design >  Is it ok to simply cover a CircularProgressIndicator with an Image in compose?
Is it ok to simply cover a CircularProgressIndicator with an Image in compose?

Time:02-17

I am showing an Image() loaded from a URL in compose which works great. While I am getting the image from the server I want the user to see a circular spinner so that he knows that something is coming. After the image is loaded the spinner should be replaced by the loaded image. The issue is that even after receiving the URL Image will still take a few seconds to render the actual bitmap on the screen. Currently I simply place both the Image and a CircularProgressIndicator overlapping each other in a Box. That way, the image, once loaded, simply overlaps the progress spinner and gives the impression of "loading complete". I am basically "faking it" as the spinner is still there behind the image.

My question is if this approach is the recommended one or if there are any negative performance implications since afaic the spinner will still be turning behind the image. Does anyone know a better/more-correct way? I haven't seen any OnRenderingComplete callback in the Image composable so far.

here my code

Box(modifier =Modifier.padding(2.dp), contentAlignment = Alignment.Center ){
    CircularProgressIndicator(modifier = Modifier
            .size(44.dp)
            .padding(3.dp),
        color = Color.White)
    Image(
        painter = rememberImagePainter(URL),
        contentDescription = null,
        modifier = Modifier
            .size(50.dp)
            .clip(CircleShape)
    )
}

TL;DR

It seems to me that my approach is relatively harmless when there is only one spinner and image on a screen (its simplicity might even render it justified) BUT I ask myself if it would also work If I used this approach on a LazyColumn with several images per row.

CodePudding user response:

The approach with a Box is totally fine, but you can use painter state to display the indicator only while it's loading like this:

val painter = rememberImagePainter(URL)
if (painter.state is ImagePainter.State.Loading) {
    CircularProgressIndicator(Modifier)
}
Image(
    painter = painter,
    contentDescription = null,
    modifier = Modifier
)
  • Related