without initial value so I don’t have to come up with some empty object while the ui waits for the ViewModel to figure out what should be drawn. But when I want to log each emission it breaks because
Flow<T>.collectAsState
does require an initial.
Copy code
class ViewModel {
val myStateFlow = _myStateFLow
.onEach { logger.i("check $it out!") }
// onEach casts it to Flow, not a StateFlow any more :(
}
Any ideas for a workaround?
s
Scott Kruse
10/30/2021, 2:25 AM
Idk I just define an initial default state now
k
knthmn
10/30/2021, 7:24 AM
In you specific use case, you can launch another coroutine to collect the
StateFlow
and log the value.
s
Steffen Funke
10/30/2021, 8:13 AM
Can
stateIn
help? This converts a (cold)
Flow
into a (hot)
StateFlow
- also requires an initial value, but you can just use the same there as you have used for
_myStateFlow
.
Disclaimer: I have not tested if t works the same with an already “hot”
StateFlow
under the hood - but I’d expect that it should:
Copy code
class ViewModel {
val myStateFlow = _myStateFLow
.onEach { logger.i("check $it out!") }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(3000), "Initial value") // you get back a StateFlow!
}
👀 1
Steffen Funke
10/30/2021, 8:16 AM
I guess that is the way to go, as answered here re by @elizarov
The design of
stateIn
operator (…) fully covers the case of missing state flow operator. Any chain of operators on a state flow can be materialized into another