mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-11-22 08:13:49 +00:00
PaginatedIterable
This commit is contained in:
parent
3837ae237d
commit
f78e81d175
@ -2,6 +2,9 @@
|
||||
|
||||
## 0.4.8
|
||||
|
||||
* `Pagination`
|
||||
* Add `PaginatedIterable` and `PaginatedIterator`
|
||||
|
||||
## 0.4.7
|
||||
|
||||
* `Ktor`
|
||||
|
@ -0,0 +1,41 @@
|
||||
package dev.inmo.micro_utils.pagination.utils
|
||||
|
||||
import dev.inmo.micro_utils.pagination.*
|
||||
|
||||
class PaginatedIterator<T>(
|
||||
pageSize: Int,
|
||||
private val countGetter: () -> Long,
|
||||
private val paginationResultGetter: Pagination.() -> PaginationResult<T>
|
||||
) : Iterator<T> {
|
||||
private var pagination = FirstPagePagination(pageSize)
|
||||
private val currentStack = mutableListOf<T>()
|
||||
override fun hasNext(): Boolean = currentStack.isNotEmpty() || (countGetter() < pagination.lastIndexExclusive)
|
||||
|
||||
override fun next(): T {
|
||||
if (currentStack.isEmpty()) {
|
||||
val resultPagination = paginationResultGetter.invoke(pagination)
|
||||
pagination = resultPagination.nextPage()
|
||||
currentStack.addAll(resultPagination.results)
|
||||
require(currentStack.isNotEmpty()) { "There is no elements left" }
|
||||
}
|
||||
return currentStack.removeFirst()
|
||||
}
|
||||
}
|
||||
|
||||
class PaginatedIterable<T>(
|
||||
private val pageSize: Int,
|
||||
private val countGetter: () -> Long,
|
||||
private val paginationResultGetter: Pagination.() -> PaginationResult<T>
|
||||
) : Iterable<T> {
|
||||
override fun iterator(): Iterator<T> = PaginatedIterator(pageSize, countGetter, paginationResultGetter)
|
||||
}
|
||||
|
||||
/**
|
||||
* Will make iterable using incoming [countGetter] and [paginationResultGetter]
|
||||
*/
|
||||
@Suppress("NOTHING_TO_INLINE")
|
||||
inline fun <T> makeIterable(
|
||||
noinline countGetter: () -> Long,
|
||||
pageSize: Int = defaultMediumPageSize,
|
||||
noinline paginationResultGetter: Pagination.() -> PaginationResult<T>
|
||||
): Iterable<T> = PaginatedIterable(pageSize, countGetter, paginationResultGetter)
|
Loading…
Reference in New Issue
Block a user