Is there a way to map a `StateFlow<T>` to a ...
# coroutines
l
Is there a way to map a
StateFlow<T>
to a
StateFlow<R>
? I have a
MutableStateFlow<MyEnum>
in a view model, but I want it private to expose publicly a
StateFlow<String>
j
.map
?
l
It returns a
Flow
, not a
StateFlow
But I would want basically that
j
maybe map + stateIn
☝️ 2
l
Not bad. The only problem I have with this is that
stateIn
is a `suspend fun`… So I can’t assign my variable directly like a simple map would allow
Oh but not all
stateIn
are
suspend fun
s
How would that work? If it would return a
StateFlow<R>
, how would the
map
function reverse map the latest value from a
T
to an
R
, when assigning a new value to that
StateFlow<R>
if it were implemented by a MutableStateFlow? And this is just for
map
. How would this work for
filter
? Etc.. Using stateIn helps by layering another statefull flow on top of the returned Flow
☝️ 1
r
MutableStateFlow
would need to go backwards, but I don't see a reason why you couldn't map a
StateFlow
backed by a
MutableStateFlow
into something like a
ReadOnlyStateFlow
.
g
"ReadOnlyStateFlow" is StateFlow, isn't?
r
I think the only actual implementation of
StateFlow
is
MutableStateFlow
(or rather
StateFlowImpl
, which stores a value). For map support, you would need a new implementation that doesn't store it's own state or support updates. But I think it would be exposed as just
StateFlow
, yeah.
g
StateFlow is Read only, same as List or Map are read only, not immutable
r
I thought it was too, but there's actually two classes that implement StateFlow: StateFlowImpl which also implements MutableStateFlow, and ReadonlyStateFlow that doesn't. Of course, ReadonlyStateFlow is just a wrapper around a StateFlow, so it has to be backed by a MutableStateFlow eventually, but I could see map being implemented using it. Any StateFlow implementation that supports map would need a different implementation that updates when it's source does, and wouldn't support writes.
g
mmap being implemented using it?
anyway, I really think that this attempt to make 2-way Flow is broken by definition