I have a sealed class `CanvasElement` and two subc...
# compose
s
I have a sealed class
CanvasElement
and two subclasses
CanvasElement.Text
and
CanvasElement.Image
. Then I have a list like
val elements = mutableStateListOf<CanvasElement>()
. How can I recompose my composables when I change an element in my list to the same element but a different property which is only present in
CanvasElement.Text
and
CanvasElement.Image
and not in
CanvasElement
. Something like this:
Copy code
sealed class CanvasElement(open val id: String, open val position: Offset) {
    data class Text(val size: Float, override val position: Offset, open val id: String): CanvasElement(id, position)
    data class Image(val size: IntSize, override val position: Offset, open val id: String): CanvasElement(id, position)
}

val elements = mutableStateListOf<CanvasElement>()

fun modifyElement(id: String, newElement) {
    // find index of id
    ...
    elements[index] = newElement
}
Then if I modify one of my text elements by changing its size, I want my Text composable to recompose:
Copy code
modifyElement((myElement as CanvasElement.Text).copy(size = newSize))

@Composable
fun Element(element: CanvasElement) {
    when(element) {
        is CanvasElement.Text -> Text("text", size = element.size) // does not recompose when size changes
        is CanvasElement.Image -> ... // does not recompose when size changes
    }
}
But the recomposition isn't happening and the text size stays the same. Is it not possible? Do I have to keep separate lists for
CanvasElement.Text
and
CanvasElement.Image
?
v
elements
is mutableState of
CanvasElement
list, so changes would occur if we change the list, I think you need to have a new list with prev elements unchanged and the new element changed in that no? that's what you are doing in modify fun, did you debug that element list is changing or not
s
Yep I'm doing that in
modifyElement
and the list is changing but the composables don't recompose. Anyways I've migrated
CanvasElement
to hold `MutableState`s and that seems to work.
👍 1