在UI中显示之前组合两个分页数据流



我有这个回收器视图,它使用PagingDataAdapter显示分页数据。当向服务发出单个请求时,它工作得很好,但有时我需要发出两个请求来获取旧事件和新事件,并在我的回收器视图中显示它们。在向用户显示分页数据之前,是否有一种方法可以将这两个分页数据流组合在一起?实际上,如果我发出两个请求,由于submitData方法中的invalidate(),只有最后一个请求保留。

这是当前的实现,没有按我需要的方式工作:

private fun fetchEvents() {
fetchEventsJob?.cancel()
binding.cameraVmsEventsRecycler.adapter = null
fetchEventsJob = lifecycleScope.launch {
cameraViewModel.searchCameraEvents(
cameraId = videoDetector.id,
dateTo = if(eventsByDate) "" else dayPickerDateTo,
pageSize = REQUEST_LIMIT
cameraViewModel.filtersApplied
).collectLatest { eventsCollection ->
val events = eventsCollection.map { event ->

CameraEventModel.CameraEventItem(
VideoEventModel(
event.eventId,
event.faceId,
null,
event.state
)
)
}.insertSeparators {
before: CameraEventModel.CameraEventItem?, after: CameraEventModel.CameraEventItem? ->
renderSeparators(before, after)
}
binding.cameraEventsRecycler.adapter = eventsAdapter
eventsAdapter.submitData(events)
}
}
}

使用不同的参数调用fetchEvents()时,由于submitData(),只有最后一个数据流保留。有没有办法让我做我想做的事?我不能在这个项目中使用Room。

您显式调用collectLatest:它在新项目发出时取消集合。效果是,如果在调用submitData()之前在收集器lambda中使用suspend,则只能从流中获得最后一项。

如果你想使用searchCameraEvents中的所有项目,你可能需要使用toList():

val flow = cameraViewModel.searchCameraEvents(/*...*/)
val eventsCollection: List<PagingData<List<Event>>> = flow.toList()
val events = eventsCollection
// get list out of paging data
.flatMap { it.data }
// flatten list of lists
.flatten()
// map as needed
.map { event ->
CameraEventModel.CameraEventItem(/*...*/)
}

注意,这里处理的是分页数据。你要确保保持一个适当的顺序。另外,如果从流中检索多个页面,实际上就会以某种方式跳过分页机制。因此,您可能还需要跟踪这一点,以免在UI中产生重复。

最新更新