commonMain.dev.inmo.micro_utils.pagination.utils.PaginatedIterable.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of micro_utils.pagination.common-jvm Show documentation
Show all versions of micro_utils.pagination.common-jvm Show documentation
It is set of projects with micro tools for avoiding of routines coding
package dev.inmo.micro_utils.pagination.utils
import dev.inmo.micro_utils.pagination.*
class PaginatedIterator(
pageSize: Int,
private val countGetter: () -> Long,
private val paginationResultGetter: Pagination.() -> PaginationResult
) : Iterator {
private var pagination = FirstPagePagination(pageSize)
private val currentStack = mutableListOf()
override fun hasNext(): Boolean = currentStack.isNotEmpty() || (countGetter() < pagination.lastIndexExclusive)
override fun next(): T {
if (currentStack.isEmpty()) {
val resultPagination = paginationResultGetter.invoke(pagination)
currentStack.addAll(resultPagination.results)
require(currentStack.isNotEmpty()) { "There is no elements left" }
pagination = resultPagination.nextPage()
}
return currentStack.removeFirst()
}
}
class PaginatedIterable(
private val pageSize: Int,
private val countGetter: () -> Long,
private val paginationResultGetter: Pagination.() -> PaginationResult
) : Iterable {
override fun iterator(): Iterator = PaginatedIterator(pageSize, countGetter, paginationResultGetter)
}
/**
* Will make iterable using incoming [countGetter] and [paginationResultGetter]
*/
@Suppress("NOTHING_TO_INLINE")
inline fun makeIterable(
noinline countGetter: () -> Long,
pageSize: Int = defaultPaginationPageSize,
noinline paginationResultGetter: Pagination.() -> PaginationResult
): Iterable = PaginatedIterable(pageSize, countGetter, paginationResultGetter)