https://kotlinlang.org logo
Title
a

Alexander Maryanovsky

05/26/2022, 8:41 AM
I have a data type that exposes its (many) properties via `StateFlow`s. Now, I want to write a function that will take an instance and return a
String
describing that object, based on its properties, and then I want to display it somewhere in the UI. How should I do that? I’m thinking of two options: 1. Make the function inline and
collectAsState
all the properties it uses. 2. Make the function return a
Flow
and then
stateIn().collectAsState()
where I want to use it. What do you think is better? Maybe there are other, better options?
z

Zach Klippenstein (he/him) [MOD]

05/26/2022, 11:47 AM
Neither is inherently better, it depends. The former requires the function to be composable, the latter does not. It’s probably easier to test the latter because you don't need a compose runtime. But the code for combining large numbers of flows into another flow is probably gonna be more gnarly than collecting each flow individually in a composable.
c

Casey Brooks

05/26/2022, 2:10 PM
As an alternative, you might be better off restructuring that class to only hold a single
StateFlow
with a large
data class
containing properties for everything you currently have as individual StateFlows, using
state.update { it.copy(...) }
to make updates to it. I’ve found it to be much easier to work with and reason about when you have that single object holding all the state, and it’s a lot easier to split it out into individual streams (
state.map { it.property }
) than it is to combine multiple streams into one. Using individual
StateFlows
assumes that they are independent streams of data, which I’ve found to rarely be the case. But when you have a single StateFlow, you can easily add properties for individual pieces of data, but you can also easily combine those properties and have derived values just by computing them in the class body. Not to mention if you need to update multiple properties at once, you will get a single atomic change, while individual StateFlows may have a period of time where the values are inconsistent as you update each one individually.
☝️🏻 1
m

Matthew Laser

05/26/2022, 3:50 PM
Without knowing your use case or exact architecture, you might consider transforming your data in an earlier layer or father up the flow “chain”
a

Alexander Maryanovsky

05/26/2022, 4:26 PM
In my case there are many properties, even an unlimited number if them (a map of StateFlows), but the function only actually uses a limited number of them. I ended up combining the flows because I had some local functions inside that function, and that's not supported for an inline function.
But thanks for the suggestion. I’ll have another tool in my arsenal.