Am I doing the right thing with these nested state...
# flow
c
Am I doing the right thing with these nested state flows? For example:
Copy code
data class MyDomainObject(
  val id: String,
  val enabled: StateFlow<Boolean>
)

val myDomainObjects: StateFlow<List<MyDomainObject> = /* This data comes from somewhere */

// I would like a list of objects which have `enabled.value == true`, and
// I would like this to be updated any time any `enabled` state changes
val enabledObjects: Flow<List<MyDomainObject> = myDomainObjects.transform { objects ->
  combine(*objects.map { it.enabled }.toTypedArray()) { enabledStates ->
    emit(objects.filterIndexed { index, _ -> enabledStates[index] })
  }
}
The implementation seems slightly wrong, the way I’m using
index
to emit objects which are enabled. But I don’t see another way to do this. Any advice? Thanks in advance.
It’s worth noting that I haven’t run this code yet… perhaps it doesn’t work as I expect but I think it should
e
why not
myDomainObjects.map { list -> list.filter { it.enabled } }
?
c
I believe this would only update when
myDomainObjects
updates, not when the individual
enabled
states update
e
oh I see, that's what's happening instead of the whole state being re-emitted…
at the very least, you want to use
transformLatest
or similar so that you switch to a new set of objects when emitted
c
Ok, thanks for the feedback
e
this would avoid needing to use indices
Copy code
myDomainObjects.flatMapLatest { objects ->
    combine(
        objects.map { object ->
            object.enabled.map { if (it) object else null }
        }
    ) { it.filterNotNull() }
}