Android 回收站视图最初总是空的

Android recycler view initially always empty

我有一个像这样的视图模型 -

private val viewState = SchoolsViewState()

    fun onViewOpened() =
        Transformations.map(schoolUseCase.performAction(SchoolAction.GetList)) {
            when (it) {
                is SchoolResult.Loading -> viewState.copy(loading = true)
                is SchoolResult.ListContent -> viewState.copy(loading = false, listData = it.schoolList)
                is SchoolResult.Error -> viewState.copy(loading = false, error = it.error)
                else -> viewState.copy(loading = false)
            }
        }

viewState class 看起来像那样 -

data class SchoolsViewState(
    val loading: Boolean = false,
    val schoolList: List<SchoolModel> = emptyList(),
    val error: SchoolResult.ErrorType? = null
)

Fragment 视图模型观察代码如下所示 -

viewModel.onViewOpened().observe(this, Observer {
//Handling the SchoolsViewState here
            swipeContainer.isRefreshing = it.loading

            if (it.schoolList.isNullOrEmpty()) {
                view?.recycler_view?.visibility = View.GONE
                view?.empty_view?.visibility = View.VISIBLE
            } else {
                view?.recycler_view?.visibility = View.VISIBLE
                view?.empty_view?.visibility = View.GONE
                view?.recycler_view?.adapter = schoolAdapter
                myAdapter.setSchoolList(it.schoolList)
            }
        })

问题出在每次滑动刷新时,我首先看到空视图,一旦有数据,我就会看到学校列表。所以这有点 UI 不便。这是由于 viewState.copy(...) 每次刷新都会为 UI 提供新状态。我该如何克服这个问题?

您更新的适配器列表与设置为回收站视图适配器的列表不同,请参阅 bookingsAdaptermyAdapter

view?.recycler_view?.adapter = bookingsAdapter
myAdapter.setSchoolList(it.schoolList)

我觉得很奇怪

如果列表为空,则不应显示空视图,因为列表仍在加载中 - 这没有意义。相反,您应该仅在 loading = false 并且您的列表为空时显示它。在这种情况下,您真的别无选择。因此,您的代码可能如下所示:

viewModel.onViewOpened().observe(this, Observer {
//Handling the SchoolsViewState here
        swipeContainer.isRefreshing = it.loading

        // if means the loading is finished 
        if (!it.loading) {
            if (it.schoolList.isNullOrEmpty()) {
                view?.recycler_view?.visibility = View.GONE
                view?.empty_view?.visibility = View.VISIBLE
            } else {
                view?.recycler_view?.visibility = View.VISIBLE
                view?.empty_view?.visibility = View.GONE
                view?.recycler_view?.adapter = schoolAdapter
                myAdapter.setSchoolList(it.schoolList)
            }
        } else {
            // here you could show some loading progress or similar
        }
    })