I was trying to pass events from UI to viewModel using sharedFlow this is my viewmodel class
class MainActivityViewModel () : ViewModel() {
val actions = MutableSharedFlow<Action>()
private val _state = MutableStateFlow<State>(State.Idle)
val state: StateFlow<State> = _state
init {
viewModelScope.launch { handleIntents() }
}
suspend fun handleIntents() {
actions.collect {
when (it) {...}
}
}
}
and this is how i am emiting actions
private fun emitActions(action: Action) {
lifecycleScope.launch {
vm.actions.emit(action)
}
}
For the first time emission happening as expected, but then it is not emitting/collecting from the viewmodel.
Am i doing anything wrong here??
When I used collectLatest()
instead of collect()
it worked as expected
collectLatest() instead of collect() hides the problem
when you do launch{ collect() } the collect will suspend whatever it is in launch code block
so if you do
launch{
events.collect {
otherEvent.collect() //this will suspend the launched block indefinetly
} }
solution is to wrap every collect in it's own launch{} code block, collectLatest will just cancel the suspend if new event is emitted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With