Nithinjith
Nithinjith

Reputation: 1825

Coroutine Channel- Flow collect issue

I am using one activity, the multiple fragment model, in my application. I have a sharedViewModel with the coroutine Channel to send and receive data from one fragment to another fragment. Also, I have a custom Dialog fragment as a popup across the app and its user action will observe the remaining fragments. My problem here is the event send from the custom dialog is not triggering in the fragment collect part frequently(2/5 Click). I am adding the codebase for your reference.

SharedView Model Part

private val _cornerDataChannel = Channel<CornerData>()
val cornerDataEvent: Flow<CornerData> = _cornerDataChannel.receiveAsFlow()

fun updateCornerDataEvent(data: CornerData) = viewModelScope.launch {
     Log.e(TAG, "Event Added")
     _cornerDataChannel.send(data)
}

Sending part in the Custom Dialog Fragment

 private fun myToolSelectionCallBack(tool: ToolDTO) =
        viewModel.updateCornerDataEvent(CornerData.ToolData(tool))

 private fun systemStreamSelectionCallBack(stream: StreamDTO) =
        viewModel.updateCornerDataEvent(CornerData.StreamData(stream))

Receiving Part inside fragments

 private fun observeCornerItemSelectionCallBack() = lifecycleScope.launchWhenStarted {
        viewModel.cornerDataEvent.collect { event ->
            when (event) {
                is StreamData -> streamSelectionCallBack(data= event.data)
                is ToolData -> toolSelectionCallBack(data = event.data)
            }
        }
    }

In the receiver part, some user clicks are missing freqently. But it's always getting the update part under the view model.

Upvotes: 3

Views: 1916

Answers (1)

USMAN osman
USMAN osman

Reputation: 1030

This is not a problem with clicks, this is because you're using regular channels for multiple observers/receivers but it is supposed to be single receiver with regular channels. You have to use BroadcastChannels for multiple receivers with single sender. Now BrodcastChannels has been deprecated it is replaced with SharedFlow()

Note: This API is obsolete since 1.5.0. It will be deprecated with warning in 1.6.0 and with error in 1.7.0. It is replaced with SharedFlow.
Check: BroadcastChannels-OfficialDocs

Upvotes: 2

Related Questions