0

I have a RecyclerView that inherits from PagingDataAdapter, inside the adapter I have two viewHolders, they are divided by viewType, the fact is that I wrote a code that combined the body of two requests into one MutableLiveData, which can then be observed in a fragment and set its value via submitData.

private val _searchResult = MutableLiveData<Resource<PagingData<SearchItems>>>()
val searchResult: LiveData<Resource<PagingData<SearchItems>>> = _searchResult

fun getSearchResult(q: String, id: String) = viewModelScope.launch {
    _searchResult.postValue(Resource.Loading())
    val searchDeferred = async { repository.getSearch(q) }
    val channelsDeferred = async { repository.fetchChannels(id) }

    val search = searchDeferred.await()
    val channels = channelsDeferred.await()

    channels.collect {
        _searchResult.value = Resource.Success(it)
    }
    search.collect {
        _searchResult.value = Resource.Success(it)
    }
}

this is the code in the ViewModel

viewModel.searchResult.observe(viewLifecycleOwner, {
    when (it) {
        is Resource.Error -> {
            it.message?.let { it1 -> Log.d("mecal", it1) }
        }

        is Resource.Success -> {
            lifecycleScope.launch {
                it.data?.map { item ->
                    viewModel.getSearchResult(
                        args.query,
                        item.snippet?.channelId.toString()
                    )
                }
                it.data?.let { it1 -> searchAdapter.submitData(it1) }
            }
        }
    }
})

and is the code in the Fragment. The point is that this code does not work, i.e. it does not display data in the recyclerview. But I don’t know what exactly I did wrong, if you have any suggestions why it doesn’t work or there is another way, please write, I really need it!

Radin
  • 5
  • 5

1 Answers1

0

Here I have something very similar that you need. It is a chat app that uses the same RecyclerView to display 2 different viewholders depending on if the message is sent to you or you sent the message

Vojin Purić
  • 2,140
  • 7
  • 9
  • 22
  • Thanks for your answer but this does not solve my problem, since I already have a split on the ViewHolder, but in order for the data in the ViewHolder to be displayed, I need to set the data to adapter from the api – Radin Nov 27 '21 at 12:41
  • You have not even checked the code. I made this repository public just so you can see, because it is so similar to yours requirement. If you want to get better you need to try, dont just expect that people on this site will write down solution for whatever you need – Vojin Purić Nov 27 '21 at 13:29