Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedFlow in Android project not working as expected

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??

like image 779
noushad_chullian Avatar asked Sep 19 '25 12:09

noushad_chullian


2 Answers

When I used collectLatest() instead of collect() it worked as expected

like image 195
noushad_chullian Avatar answered Sep 21 '25 03:09

noushad_chullian


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

like image 28
Hessesian Avatar answered Sep 21 '25 04:09

Hessesian