I use Compose’s `fun StateFlow<T>.collectAsS...
# compose
m
I use Compose’s
fun StateFlow<T>.collectAsState()
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
Idk I just define an initial default state now
k
In you specific use case, you can launch another coroutine to collect the
StateFlow
and log the value.
s
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
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 
StateFlow
 using 
stateIn
 operator,