3

I'm loading a pretty large resource image using Coil for Jetpack Compose and it takes some tens of milliseconds to load, even hundreds when the screen is loaded for the first time. I want to not display some parts of the screen if the image isn't loaded yet. I wandered into the rememberImagePainter method's implementation but I couldn't find something to help me.

daniyelp
  • 915
  • 1
  • 11
  • 26
  • I was running into the same issue (painter.state not triggering callbacks as I'd expect). In my case, it would always stay in the "Loading" state. In the documentation for `rememberAsyncImagePainter` (ImagePainter appears to be deprecated in more recent versions). It mentions that there are some gotchas with specific implementations. For example when using LazyRow or LazyColumn, you need to make sure either the height or width are bounded. In my case, adding `.size(Size.ORIGINAL)` to my ImageRequest builder did the trick. Something similar might be causing this in your older version. – Nick Borisenko Jun 02 '22 at 21:57

2 Answers2

2

You can achieve this behavior by using painter.state

val painter = rememberImagePainter(.....)

val painterState = painter.state

Now you can compare the coil states like error, loading, and success very easily

if (painterState is ImagePainter.State.Loading) {
showLoadingDialog()
}

if(painterState is ImagePainter.State.Success) {
showContent()
}
RaBaKa 78
  • 1,115
  • 7
  • 11
2

There is an option to pass a listener in the builder:

rememberImagePainter(data = "url or something", builder = {
    listener(object : ImageRequest.Listener {
        override fun onCancel(request: ImageRequest) {
            ...
        }

        override fun onError(request: ImageRequest, throwable: Throwable) {
            ...
        }

        override fun onStart(request: ImageRequest) {
            ...
        }

        override fun onSuccess(request: ImageRequest, metadata: ImageResult.Metadata) {
            ...
        }
    })
})

However if you just want to show a placeholder image, it's easiest to use the option placeholder(...) which is also available in the builder:

rememberImagePainter(data = "url or something", builder = {
    placeholder(R.drawable.image_placeholder)
})
Stephan
  • 15,704
  • 7
  • 48
  • 63
  • That's the thing that I've tried before posting the question. It didn't work. Maybe this behaves as expected only when loading a resource from the internet. – daniyelp Feb 01 '22 at 17:25
  • If that is the case then I would assume it's a bug. This https://github.com/coil-kt/coil/issues/1037 issue might be related. – Stephan Feb 02 '22 at 08:03