0

在我的情况下,我获取了一个数据列表并在RecyclerView使用中显示它,PagingDataAdapter但是在导航到另一个Fragment然后导航回上一个Fragment(A - > B - > A)之后出现了问题,所以在再次重新观察到之后LiveData,我得到了来自分页源的最新值,我没有得到所有列表数据。

这是我写的代码:

OrdersFragmentViewModel.kt

class OrdersFragmentViewModel @ViewModelInject constructor(
        private val restRepository: RestRepository,
        @Assisted state: SavedStateHandle
) : ViewModel() {

    var orderStatus: Int? = null

    private val _progressBar = MutableLiveData<Boolean>()
    val progressBar: LiveData<Boolean> = _progressBar

    private val currentStatus = state.getLiveData(CURRENT_STATUS, orderStatus)

    //getting data from Paging source 
    val orders = restRepository.getAllOrders(
            OCApplication.preferencesManager.token,
            status = null,
    ).cachedIn(viewModelScope)

}

分段

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    binding.swiperefresh.setOnRefreshListener(this)

    ordersAdapter = OrdersAdapter(this, preferencesManager)
    binding.orderList.adapter = ordersAdapter
    handelOrdersStates()
    observe(viewModel.orders, ::setOrders)
    handleHomePopup()
    onCreateFirstOrderClick()

}

private fun setOrders(orders: PagingData<OrderDetails>) {
    ordersAdapter.submitData(viewLifecycleOwner.lifecycle, orders)
}

分页数据源

private const val ORDERS_STARTING_PAGE_INDEX = 0

class OrdersDataSource(
        private val remoteRepository: RestRepository,
        private val token: String,
        private val status: Int?,
) : PagingSource<Int, OrderDetails>() {


    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, OrderDetails> {
        val position = params.key ?: ORDERS_STARTING_PAGE_INDEX

        return try {
            val response = remoteRepository.getAllOrders(token, status, position, params.loadSize)
            val orders = response.data?.data?.data ?: ArrayList()
            val ordersFiltered = if (status == null) {
                orders.filter {
                    it.clientPurchaseOrderStatus != ClientPurchaseOrderStatus.WaitingForApprovalOwner.ordinal
                }
            } else {
                orders.filter {
                    it.clientPurchaseOrderStatus <= ClientPurchaseOrderStatus.WaitingForApprovalFromClient.ordinal
                            || it.clientPurchaseOrderStatus == ClientPurchaseOrderStatus.WaitingForApprovalOwner.ordinal
                }
            }

            LoadResult.Page(
                    data = ordersFiltered.sortedByDescending { it.createdAt.getOrdersTimeStamp() },
                    prevKey = if (position == ORDERS_STARTING_PAGE_INDEX) null else position - params.loadSize,
                    nextKey = if (orders.isEmpty()) null else position + params.loadSize
            )
        } catch (exception: IOException) {
            LoadResult.Error(exception)
        } catch (exception: HttpException) {
            LoadResult.Error(exception)
        }
    }
}
4

0 回答 0