Is there any kind of flow that mixes state and sha...
# flow
m
Is there any kind of flow that mixes state and shared flow? I would like to have a flow that emits every time a new value (even if the value is equal to the last value) but has a
.value
parameter so that I can query the parameter at any point in time? (sort of a stateful share flow 🙂 )
e
Just box your values into
class Box<T>(val value: T)
(not a data class) and every time you emit a Box to a state flow it will be treated like a new value.
m
thanks.. one question, is there a reason why a stateflow can’t take a comparator as inputparameter during creation?
btw.. wont the boxing give quite a lot of unboxing as well,
stateflow.value.value
not the nicest solution, even if it works.
e
There is a good reason not to accept an arbitrary comparator. You see, if I encounter
StateFlow<SomeType>
anywhere in the codebase I know exactly how it is going to behave without hunting down the place where it is created.
To avoid boxing you can also reconsider equals contract of the class you submit to your state flow. Maybe that class should not a data class in the first place, but be compared entirely by reference.
m
I understand your arguments, but not totally agreeing with them 🙂 . As you said, you can always override the equals method of the class or dataclass so you can’t know exactly how the flow behaves without some further investigation. Anyway, thanks for the tips and i’m sure i’ll find a solution.
n
Does
SharedFlow.replayCache
when replay is 1 not work for some reason?
m
Its not really for when i consume it in a new place. One of my scenarios is that i have a consumer that just wants to get the changes which i can do with
distinctUntilChanged
on a sharedFlow. another consumer wants to know if the value is “fresh”, i.e for each consumed value I update a timer, and if the timer runs out I know that the value is old, and might have to trigger a warning to the user. In a third place I just want to know the current state in an If statement I know that we can create this with a number of different workarounds, so it’s not really hindering me that much, but for me, the perfect Flow for this combination of consumers would either be a SharedFlow with a
value
parameter, or a StateFlow that emits every value independent on the result of the
equals
method.