https://kotlinlang.org logo
#flow
Title
# flow
c

Chris Fillmore

10/04/2021, 9:00 PM
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

ephemient

10/04/2021, 9:03 PM
why not
myDomainObjects.map { list -> list.filter { it.enabled } }
?
c

Chris Fillmore

10/04/2021, 9:04 PM
I believe this would only update when
myDomainObjects
updates, not when the individual
enabled
states update
e

ephemient

10/04/2021, 9:07 PM
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

Chris Fillmore

10/04/2021, 9:19 PM
Ok, thanks for the feedback
e

ephemient

10/05/2021, 1:09 AM
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() }
}
4 Views