Miguel Vargas
10/30/2021, 1:46 AMfun 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.
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?Scott Kruse
10/30/2021, 2:25 AMknthmn
10/30/2021, 7:24 AMStateFlow
and log the value.Steffen Funke
10/30/2021, 8:13 AMstateIn
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:
class ViewModel {
val myStateFlow = _myStateFLow
.onEach { logger.i("check $it out!") }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(3000), "Initial value") // you get back a StateFlow!
}
Steffen Funke
10/30/2021, 8:16 AMThe design ofoperator (…) fully covers the case of missing state flow operator. Any chain of operators on a state flow can be materialized into anotherstateIn
usingStateFlow
operator,stateIn