Hey, is there a simpler way to use a composable fo...
# compose
j
Hey, is there a simpler way to use a composable for placeholder image while it's loading? I assume I would need to hold specific state for this?
Copy code
Image(
                painter = rememberImagePainter(
                    data = url,
                    builder = {
                        placeholder(...) // <-- I want to have a composable placeholder instead
                        crossfade(true)
                    }
                ),
c
Extract the painter to a val, then use a
when
to switch the content based on
painter.state
. The second transition example shows the overall idea: https://coil-kt.github.io/coil/compose/#transitions
j
Yep, thank you, I've already figured it out, will update this thread with my solution a bit later
👍 1
I ended up with the following solution, not sure if that is the cleanest approach, but it works as I wanted:
Copy code
@Composable
fun CoilImage(
    modifier: Modifier = Modifier,
    url: String?,
    builder: ImageRequest.Builder.() -> Unit = { crossfade(true) },
    contentDescription: String? = null,
    loading: @Composable (() -> Unit)? = null,
    failure: @Composable ((ImagePainter.State.Error) -> Unit)? = null
) {
    val coilPainter = rememberImagePainter(data = url, builder = builder)
    val state = coilPainter.state

    when {
        state is ImagePainter.State.Loading && loading != null -> loading()
        state is ImagePainter.State.Error && failure != null -> failure(state)
        else -> Image(
            painter = coilPainter,
            modifier = modifier,
            contentDescription = contentDescription
        )
    }
}