【问题标题】:How to set two request bodies to one RecyclerView?如何将两个请求主体设置为一个 RecyclerView?
【发布时间】:2022-01-05 00:45:19
【问题描述】:

我有一个继承自PagingDataAdapter的RecyclerView,在adapter里面我有两个viewHolder,它们是按viewType划分的,事实上我写了一个代码,将两个请求的body组合成一个MutableLiveData,然后可以观察到在片段中并通过 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)
    }
}

这是 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 是 Fragment 中的代码。关键是这段代码不起作用,即它不在recyclerview中显示数据。但是我不知道我到底做错了什么,如果您有任何建议为什么它不起作用或有其他方法,请写,我真的需要它!

【问题讨论】:

    标签: android kotlin android-recyclerview kotlin-coroutines paging


    【解决方案1】:

    Here我有一些非常相似的东西你需要。这是一个聊天应用程序,它使用相同的RecyclerView 显示2 个不同的viewholders,具体取决于消息是发送给您还是您发送了消息

    【讨论】:

    • 感谢您的回答,但这并不能解决我的问题,因为我已经对 ViewHolder 进行了拆分,但是为了显示 ViewHolder 中的数据,我需要将数据设置为来自 api 的适配器
    • 你甚至没有检查代码。我公开了这个存储库,以便您可以看到,因为它与您的要求非常相似。如果你想变得更好,你需要尝试,不要只期望这个网站上的人会写下你需要的解决方案
    猜你喜欢
    • 2017-04-02
    • 2019-05-03
    • 2018-01-10
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2012-08-06
    • 2014-10-31
    相关资源
    最近更新 更多