https://kotlinlang.org logo
Title
l

Luke

11/07/2020, 7:38 PM
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

Javier

11/07/2020, 7:39 PM
.map
?
l

Luke

11/07/2020, 7:40 PM
It returns a
Flow
, not a
StateFlow
But I would want basically that
j

Javier

11/07/2020, 7:42 PM
maybe map + stateIn
☝️ 2
l

Luke

11/07/2020, 7:50 PM
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

streetsofboston

11/07/2020, 8:03 PM
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

rnett

11/07/2020, 10:08 PM
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

gildor

11/08/2020, 11:26 PM
"ReadOnlyStateFlow" is StateFlow, isn't?
r

rnett

11/09/2020, 12:47 AM
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

gildor

11/09/2020, 4:33 AM
StateFlow is Read only, same as List or Map are read only, not immutable
r

rnett

11/09/2020, 5:35 AM
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

gildor

11/09/2020, 5:53 AM
mmap being implemented using it?
anyway, I really think that this attempt to make 2-way Flow is broken by definition