gpt4 book ai didi

android - 如何刷新分页 3 库中的页码

转载 作者:行者123 更新时间:2023-12-04 23:46:59 24 4
gpt4 key购买 nike

我正在使用第 3 页在回收站 View 中加载一些数据。我从服务器获取数据,然后将它们存储在我的本地数据库中。
所以这是我的 DAO 界面:

@Dao
interface TicketDAO {


@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(model: TicketListModel)


@Query("SELECT * FROM ticket_list ORDER BY lastModifyDate DESC , lastModifyTime DESC")
fun getTickets(): PagingSource<Int, TicketListModel>


@Query("delete from ticket_list")
fun deleteAll()


}
我假设这个接口(interface)是我的数据源类。因为我也从服务器获取数据,所以我使用了这样的远程调解器(顺便说一下,我使用 volley 从服务器获取数据):

@ExperimentalPagingApi
class TicketRemoteMediator(val ticketDatabase: TicketDAO, val context: Context) :
RemoteMediator<Int, TicketListModel>() {

private val scope = CoroutineScope(Dispatchers.Default)
private var page = 0
private var reachedEnd = false
override suspend fun load(
loadType: LoadType,
state: PagingState<Int, TicketListModel>
): MediatorResult {
return try {
fetchData(page = page)
page += 1
Log.i("Log","page is $page")
MediatorResult.Success(endOfPaginationReached = reachedEnd)
} catch (e: Exception) {
page -= 1
MediatorResult.Error(e)
}

}

private fun fetchData(page: Int) {
val request = object : JsonObjectRequest(
Method.GET, Address().getTicketAPI(page), null, Response.Listener {
reachedEnd = true
val info = it.getJSONArray("results")
for (i in 0 until info.length()) {
val data = info.getJSONObject(i)
scope.launch {
async(Dispatchers.Default, CoroutineStart.DEFAULT, block = {
ticketDatabase.insert(
TicketListModel(
subject = data.getString("subject"),
status = data.getString("status"),
)
reachedEnd = false
}).await()
}
}

}, Response.ErrorListener {
this.page -= 1
reachedEnd = false
try {
Log.i("Log", "error in ticket remoteMediator ${String(it.networkResponse.data,Charsets.UTF_8)}")
}catch (e:Exception){
Log.i("Log", "error in ticket mediator $it")
}

}
) {
@Throws(AuthFailureError::class)
override fun getHeaders(): MutableMap<String, String> {
val token = HashMap<String, String>()
token["Authorization"] =
"Bearer ${Config().accessToken}"
return token
}
}
request.retryPolicy = DefaultRetryPolicy(10000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
val queue = Volley.newRequestQueue(context)
queue.add(request)
}
}

并使用我的 View 模型类使用数据,如下所示:
    val isLoading = MutableLiveData<Boolean>()

@ExperimentalPagingApi
val tickets= Pager(
config = PagingConfig(pageSize =5),
remoteMediator = TicketRemoteMediator(ticketDatabase = database, context = context)
) {
database.getTickets()

}.liveData.cachedIn(viewModelScope).also {
isLoading.value = false
}
我的 fragment 中有这段代码:
            viewModel.tickets.observe(viewLifecycleOwner, Observer {
viewLifecycleOwner.lifecycleScope.launch {
adapter.submitData(it)
}
})
回收器 View 适配器的哪一部分是:

class TicketListAdapter : PagingDataAdapter<TicketListModel, TicketListAdapter.ViewHolder>(
diffCallback = object : DiffUtil.ItemCallback<TicketListModel>() {
override fun areItemsTheSame(oldItem: TicketListModel, newItem: TicketListModel): Boolean {
return oldItem.ticket_id == newItem.ticket_id
}
override fun areContentsTheSame(
oldItem: TicketListModel,
newItem: TicketListModel
): Boolean {
return oldItem == newItem
}

}
) {

...
}
现在,我有两个问题:
第一:
有一段时间我的用户想要刷新列表。使用滑动刷新。
所以我为此设置了这行代码,但没有任何 react :
        binding.refresh.setOnRefreshListener {
database.getTickets().invalidate()
}
其次:
即使用户尚未滚动,来自服务器的分页库请求也很多。事实上,当我登录时,我看到有超过 20 个请求被发送到服务器,而在 1 或 2 个请求之后,所有信息都可以从服务器获取。
我该如何解决这些问题?

最佳答案

刷新很简单,只需调用refresh()在您的适配器上

binding.refresh.setOnRefreshListener{
pagingAdapter.refresh()
}
至于有多个请求,这可能是 pageSize你给了 PagingConfig .如果您查看其中的其他参数,您可以看到 initialLoadSize 的默认值是三倍 pageSize .这意味着它将尝试加载 pageSize *3 项目之前它是快乐的。从 Address().getTicketAPI(page) 返回的项目数量
更新:
我刚刚注意到您的 load方法总是假设我们在实际调用它来刷新和加载前一页时尝试加载下一页。这是 loadType指示我们尝试加载的方向的参数。
这是您的加载方法应该是什么样子的示例
val nextPage = when (loadType) {
LoadType.REFRESH -> 0 // we're refreshing so just reset the page
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true) // shouldn't need to prepend
LoadType.APPEND -> {
// work out the next page number
page + 1
}

return try {
fetchData(page = nextPage)
Log.i("Log","page is $nextPage")
MediatorResult.Success(endOfPaginationReached = reachedEnd)
} catch (e: Exception) {
MediatorResult.Error(e)
}

关于android - 如何刷新分页 3 库中的页码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64662560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com