我有一个这样的viewmodel-
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类看起来像这样-
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提供新状态。我该如何克服这个问题?
view?.recycler_view?.adapter = bookingsAdapter
myAdapter.setSchoolList(it.schoolList)
对我来说这很奇怪
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
}
})