https://kotlinlang.org logo
Title
m

maxmello

09/13/2021, 2:20 PM
I just started using Flows, and in migrating my LiveData I often had the use case “generally speaking the LiveData is updated internally, but sometimes I want to manually trigger an update from outside”. An example would be some state that is read from a data source periodically, but on hitting “refresh” I want the newest value immediately. In another case, my data source (some kind of observer provided by Android) is not 100% reliable, so on hitting “refresh”, I would get the same information from another source to overwrite the current value. So in the world of Flow, I might have a
callbackFlow + stateIn
or a flow created with
combine + stateIn
. Now this is a
StateFlow
which has no
emit
that is callable from “outside”. Is there a way to achieve this, basically a
.toMutableStateFlow()
?
t

Tijl

09/13/2021, 2:22 PM
if you make a new
MutableStateFlow
you can do
myStateFlow.collect(someOtherFlow)
m

maxmello

09/13/2021, 2:49 PM
I see, I did
immutableStateFlow.collect { newValue -> mutableStateFlow.update { newValue } }
, I assume this is what you mean? A function to directly pass in another flow is marked as @InternalCoroutinesApi for me
t

Tijl

09/13/2021, 2:53 PM
I mean you make your
MutableStateFlow
that you want to emit to, and then make it collect the flow (e.g. the
callbackFlow
you mentioned). then you can do what you want, rely on values from the upstream flow, or emit directly. if you don’t want to do this because of the
InternalCoroutinesApi
then I would suggest finding another solution
and I realize I’m saying it reversed here, it’s
upstreamFlow.collect(myStateFlow)
of course
👍 1