https://kotlinlang.org logo
Title
w

William Reed

05/10/2022, 5:12 PM
I have a collection of `Node`s which all have a
StateFlow<NodeState>
property. I also have a
NodeManager
which in turn has a
MutableList<Node>
(which is just exposed as a
List<Node>
. At my UI level I want to display something based on each `Node`’s state. it starts to get a little weird since I need to observe each nodes state flow as well as account for the `NodeManager`s collection of nodes possibly changing. Any suggestions for how to approach this such that in my UI level I can end up with a
List<NodeState>
so I can render views from it? I’ve tried exposing a
StateFlow<List<Node>>
from the
NodeManager
but then from the UI level I would need to somehow manage the collection of each node / the node’s possibly getting removed or added
n

Nick Allen

05/10/2022, 6:44 PM
If you want to listen for changes to state it must be observable so it can't just be a
List
. What about something along the lines of:
class Node {
    val state = MutableStateFlow<Int>(0)
}

class NodeManagerNeedsBetterName {
    val nodes = MutableStateFlow<List<Node>>(emptyList())
    val nodeStates = nodes.flatMapLatest { nodeList ->
        combine(nodeList.map { it.state }) { it.toList() }
    }
}
w

William Reed

05/10/2022, 6:46 PM
sure i was just hand waving the
List
part (and I already have other names for node/ node manager just simplifying here). Let me think about that snippet you sent though