Hi all :android-wave: , How to combine and collect...
# compose-android
a
Hi all 👋 , How to combine and collect multiple flows in a type safe way? Current code
Copy code
combine (flow1, flow2, flow3, ...) { data1, data2, data3, ... ->
  DataStructure(data1, data2, data3, ...) // DataStructure would be Pair(), Triple, etc depending on number of flows
}.collectLatest { (data1, data2, data3, ...) ->
   // Can use all data in type safe way
}
As the above code requires
DataStructure
to be modified for any flow addition or removal from the
combine
, and also to create new custom
DataStructure
for more than 3 data. How can I change this in a type safe way?
Copy code
combine (flow1, flow2, flow3, ...) { dataList ->
  dataList
}.collectLatest { dataList ->
   // Can NOT use all data in type safe way, the data type is Array<Any?>
}
This code loses the type safety as the data list is
Array<Any?>
.
s
What's wrong with the first option?
a
I have to create lot of
DataStructure
classes and it is lot of boiler plate code.
Also,
the above code requires
DataStructure
to be modified for any flow addition or removal from the
combine
s
If you really want to, you can make your own
combineLatest
function, or rather 12 functions or however many parameters you want to combine, which will internally do a combine, create that 1-12 parameter instance, and then pass the items individually inside the lambda.
a
Okay, that sounds like a good solution. So, there is no out of the box solution 😅 ?
s
Some prior discussions here too https://github.com/Kotlin/kotlinx.coroutines/issues/1484#issuecomment-699600367 They give a solution too, without the data class I was suggesting, but just using the array one and casting appropriately since you know what the types would be in those scenarios
So, there is no out of the box solution
No AFAIK
🆗 1
a
Thanks for sharing this. thank you color