【发布时间】:2020-11-14 04:40:18
【问题描述】:
如何使用 paging3 库,其中每个页面的大小都可以变化?
我正在尝试显示一个日历,其中每个页面都由一周表示,并且每周可以有 0 到 n 个会议。
我想我可以在我的 DataSource 中将今天作为分页键用于初始加载,将 ±7 天用于上一页/下一页,例如:
class CalendarPagingSource @Inject constructor(
private val calendarApi: CalendarApi,
) : RxPagingSource<ZonedDateTime, Meeting>() {
override fun loadSingle(params: LoadParams<ZonedDateTime>): Single<LoadResult<ZonedDateTime, Meeting>> {
val page = params.key ?: ZonedDateTime.now()
val startDate = page.format(ofPattern("yyyy-MM-dd"))
return calendarApi
.myMeetings(startDate)
.map { toLoadResult(page, it) }
.onErrorReturn { LoadResult.Error(it) }
}
private fun toLoadResult(key: ZonedDateTime, entries: List<Meeting>): LoadResult<ZonedDateTime, Meeting> {
val now = ZonedDateTime.now()
// Do not load more than 90 days before and after today
return LoadResult.Page(
data = entries,
prevKey = if (now.minusDays(90L).isBefore(key)) key.minusDays(DATE_RANGE) else null,
nextKey = if (now.plusDays(90L).isAfter(key)) key.plusDays(DATE_RANGE) else null
)
}
}
但我面临一个问题,即我无法提前知道特定一周将举行多少次会议。
class CalendarRepository @Inject constructor(
private val pagingSource: CalendarPagingSource
) {
fun myMeetings(): Observable<PagingData<Meeting>> {
return Pager(
config = PagingConfig(
pageSize = ???,
enablePlaceholders = false
),
pagingSourceFactory = { pagingSource }
).observable
}
}
有没有一种方法可以让我不必指定 pageSize,只需使用分页键(在本例中为 ZonedDateTime)进行分页?
【问题讨论】:
标签: android android-jetpack android-paging-3