2

I want to create a shared view model for communication between MainActivity to fragments. I decided to use share flow for managing events.

 private val _sharedChannel: MutableSharedFlow<SharedEvent> = MutableSharedFlow(
        replay = 0,extraBufferCapacity=0,onBufferOverflow = BufferOverflow.SUSPEND)
    val sharedChannel = _sharedChannel.asSharedFlow()

I don't need to cache the last event, not even when orientation changes.. so I set "replay = 0"

When I collect the events only in my main activity - everything works fine:

   lifecycleScope.launchWhenStarted {

        gamePlaySharedViewModel.sharedChannel.collect { event->
            SnappLog.log("GamePlayContainer-> sharedChannel EVENT: $event ")
            when(event){
                GamePlaySharedViewModel.SharedEvent.OnBackPress -> {
                    onBackPressed()
                }
                is GamePlaySharedViewModel.SharedEvent.BlockScreen -> {
                    blockScreen(event.isBlocked)
                }
                else -> {

                }
            }

        }
    }
}

When adding a second subscriber to another fragment - both of the subscribers stop receiving events after the first one (the first event send successfully.. ) what can I do to subscribe for multi MutableSharedFlow? I've tried to increase the number of "replay" and to change the "onBufferOverflow" - nothing seems to work..

General Grievance
  • 4,555
  • 31
  • 31
  • 45
digitalmidges
  • 826
  • 3
  • 13
  • 24
  • How does the second subscriber looks like? Does it suspend when receiving an item? – esentsov Apr 14 '21 at 17:46
  • The second subscriber looks the same, what do you mean "Does it suspend when receiving an item"? – digitalmidges Apr 14 '21 at 23:16
  • 1
    As you have `BufferOverflow.SUSPEND` policy, a new item cam be emitted when the previous one has been consumed by **all** subscribers only. That means if one of you subscriber is slow in processing items, the producer suspends and waits for it. – esentsov Apr 15 '21 at 02:54
  • Thanks @esentsov its seems that I had to cancel the coroutines job when one of my fragment was pausing – digitalmidges Apr 16 '21 at 06:37
  • adsCollectorJob = lifecycleScope.launch { adsManager.adsManagerChannel.collect { event -> SnappLog.log("QuestionFragment-> adsManagerChannel event: $event") when (event) { is AdsManger.AdsManagerEvent.NotifySkipLevelRewarded -> { notifySkipLevelRewarded() } } } } – digitalmidges Apr 16 '21 at 06:37
  • override fun onPause() { super.onPause() adsCollectorJob?.cancel() } – digitalmidges Apr 16 '21 at 06:38

0 Answers0