Hey! :wave: Is there any way to map values emitted...
# coroutines
n
Hey! 👋 Is there any way to map values emitted by a
StateFlow
and still have a
StateFlow
and not a
Flow
?
stateflow.map(::mapper)
returns a
Flow
.
j
To have another
StateFlow
you would need to store a new state and to have a coroutine that collects the source flow into the new one. You could use stateIn after
map
to do that for you behind the scenes.
n
😞 Ok, sounds a bit weird coming from Rx, but looks doable. Thanks!
j
What would you do in Rx? Also, why do you need a
StateFlow
as a result there (why is
Flow
not sufficient)?
n
I need a
StateFlow
just to have better integration with Jetpack Compose. In
Rx
a simple
map
on a
BehaviourSubject
would suffice, if I’m not mistaken.
s
The return type of the
map
method on
BehaviorSubject
is a plain
Observable
(which is comparable to a plain
Flow
), which gives you the same type of problem that you are asking about. http://reactivex.io/RxJava/3.x/javadoc/io/reactivex/rxjava3/subjects/BehaviorSubject.html
n
🤔 You’re absolutely right.
m
a
You can, but you need to supply your own initial value since the collection doesn't begin until initial composition has completed
âž• 3
Most of the time when people ask for this is because they are using StateFlow for hot state instead of snapshots, and snapshots can do this natively https://github.com/Kotlin/kotlinx.coroutines/issues/2631#issuecomment-859662590
🤔 1
(example in the linked comment)
n
Yes, that’s exactly my case, Adam. I ended up re-casting my Flow to StateFlow with
stateIn
. Feels a bit weird, but it works.
h
Although compose
(Mutable) State
is nice, the advantage using
StateFlow
is multiplatform support, especially iOS.