I am very confused, I have a situation where I jus...
# compose
t
I am very confused, I have a situation where I just replace a state var with a state map, and now the state isn't being kept
Copy code
// Works
var nodeOffset by remember { mutableStateOf(DpOffset(200.dp, 300.dp)) }
DraggableCard(initialOffset = nodeOffset, onOffsetChange = { nodeOffset = it }) {
    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
        Text(text = "This One")
        Pin(direction = <http://Direction.IN|Direction.IN>)
    }
}

// Doesn't work
class NodeKey
val key = NodeKey()
val nodeOffsets = remember { mutableStateMapOf<NodeKey, DpOffset>() }
DraggableCard(initialOffset = nodeOffsets[key] ?: DpOffset(300.dp, 200.dp), onOffsetChange = { nodeOffsets[key] = it }) {
    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
        Text(text = "That One")
        Pin(direction = Direction.OUT)
    }
}
onOffsetChange is definitely being called and the map is being updated, but it never recomposes to get the new location
a
You are not remembering the key, which means the key changes on each recomposition.
t
ah
hm
but when I had it as a string it didn't work either
a
In that case you should file a bug with a reproducer.
t
but yeah remembering the key makes it work. interesting
I don't want to use string keys anyway so....
getting somewhere
Copy code
@Composable
@Preview
fun DraggableCardPreview() {
    MaterialTheme(colors = darkColors()) {
        Surface(modifier = Modifier.fillMaxSize()) {
            Graph {
                val graphNodes = listOf(
                    GraphNodeState(initialData = GeneratorNode(), initialOffset = DpOffset(200.dp, 300.dp)),
                    GraphNodeState(initialData = ConsumerNode(), initialOffset = DpOffset(300.dp, 200.dp)),
                )
                nodes(nodes = graphNodes) { data ->
                    when (data) {
                        is GeneratorNode -> {
                            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                                Text(text = "Generator Node")
                                Pin(direction = Direction.OUT)
                            }
                        }
                        is ConsumerNode -> {
                            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                                Text(text = "Consumer Node")
                                Pin(direction = <http://Direction.IN|Direction.IN>)
                            }
                        }
                    }
                }
            }
        }
    }
}
that's the sort of API I'd like to have
then the stuff that goes from pin to pin is Cord