https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

Deepak Gahlot

04/05/2021, 11:46 AM
Hello All, I'm trying to build a Search functionality using BroadcastChannel api in Coroutine.
In the ViewModel i have following code
Copy code
@ExperimentalCoroutinesApi
@VisibleForTesting
val queryChannel = ConflatedBroadcastChannel<String>()
Copy code
@FlowPreview
@ExperimentalCoroutinesApi
@VisibleForTesting
fun userQuerySearch(query: String) {
    viewModelScope.launch {
        queryChannel
            .asFlow()
            .debounce(SEARCH_DELAY_MS)
            .mapLatest {
                Log.i("mylog", "userQuerySearch: $it")
                if (it.length >= MIN_QUERY_LENGTH) {
                    questionnaireRepoImp.commoditySearch(query = query, sLiveData = searchMasterData)
                    searchMasterData.postValue(Resource.Loading())
                } else {
                    searchMasterData.postValue(Resource.Success(MasterData()))
                }
            }
    }
And from my UI which is a Composable function i update the Channel and call the function for search
Copy code
corotineScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
    questionnaireViewModel.queryChannel.send(value.value)
    questionnaireViewModel.userQuerySearch(value.value)
}
What i'm seeing that queryChannel doe not receive any text input that is being send from the UI
But if is use something like
Copy code
queryChannel.consumeEach {
    Log.i("mylog", "userQuerySearch: $it")
}
In see that the inputs are being received from the UI
I'm doing a wrong conversion to flow ?
d

Dominaezzz

04/05/2021, 12:23 PM
Why do you pass
query
as a function argument? You already have the channel, no?
try removing
debounce
m

MiSikora

04/05/2021, 12:49 PM
You don’t collect any events. You need to use either
launchIn
or
collect
on your Flow.
☝️ 1
d

Deepak Gahlot

04/05/2021, 2:35 PM
@Dominaezzz you are right, i have made that change.
3 Views