Tim Malseed
02/09/2022, 10:38 PMStateFlow
, 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?Joffrey
02/09/2022, 10:43 PMMutableStateFlow
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:
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
doesTim Malseed
02/09/2022, 11:01 PMZach Klippenstein (he/him) [MOD]
02/10/2022, 5:36 AM