I'm missing operators for StateFlow<T> such as map and transform. Example use case:
val name: StateFlow<String> = MutableStateFlow("Eric")
val greeting: StateFlow<String> = name.map { name -> "Hi $name!" }
This would be the same API Android's LiveData provides.
I think using stateIn is the way to go here.
i.e. name.map { name -> "Hi $name!" }.stateIn(...)
That way you can do more transformations between the two StateFlows without the cumulative overhead (locks) in-between.
Also, redefining operators is somewhat counter-intuitive to one of the things Flows were intending to achieve, unifying stream operations (Like the ones from Channel which were deprecated).
Where can I find more information about stateIn? Can't find it in the docs.
@NahroTo
the stateIn operator isn't available in the version 1.3.6.
The design of stateIn operator was posted for review in #2047 and, I believe, it fully covers the case of missing state flow operator. Any chain of operators on a state flow can be materialized into another StateFlow using stateIn operator, so I'm closing this issue. If anything is missing, please comment under #2047.
@elizarov What if I want to simply transform with map an already available StateFlow into a new StateFlow? I will have to explicitly cast the return of map (that is Flow) to StateFlow?
@brescia123, updating the return type is a breaking change.
Finally, please consider that a StateFlow is more expensive than a Flow, it isn't a simple cast.
Any chain of operators on a state flow can be materialized into another StateFlow using stateIn operator
We are on transit from LiveData to StateFlow, because it allows us to write more declarative code. It also means we are writing many chains. However, many state flows have stateIn in the end. Because fragment can't consume suspendable version of stateIn we always need to provide some dummy object for the state. It does not look optimal due to unnecessary memory allocation.
Just an idea, but maybe it is worth considering implement non-suspendable version of few operators, who guarantee the result will be correct. For example mapState and combineState cover almost all chains and should guarantee correctness
@neworld Can you, please, elaborate a bit on what you mean by "fragment can't consume suspendable version" and give some examples of the code you are having to write in your app.