Can someone help me understand.. If I want to cre...
# coroutines
t
Can someone help me understand.. If I want to create a
StateFlow
, I can call
MutableStateFlow()
. But, if I want to convert a Flow into a
StateFlow
, I call
stateIn()
.
stateIn()
requires a
CoroutineScope
. But
MutableStateFlow()
doesn’t. Why is that?
j
Using
MutableStateFlow
is like creating a variable which you can set. It doesn't require any coroutine. However, if you want to create a
StateFlow
out of an existing
Flow
, you need somehow to collect elements from that flow so you can set the value of the state flow. Using
stateIn
creates a coroutine which does exactly that, hence the need for a scope. You can see
stateIn
as a sort of shortcut for:
Copy code
val stateFlow = MutableStateFlow(initialValue)
scope.launch {
    flow.collect {
        stateFlow.value = it
    }
}
So as you can see, you need more than just
MutableStateFlow
to do what
stateIn
does
t
Oh yeah I see. Thanks for a great explanation!
☺️ 1
z
The flow code is quite readable and is often a great way to answer these sorts of questions: https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/flow/operators/Share.kt
🙌 2