All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.dev.inmo.micro_utils.pagination.utils.PaginatedIterable.kt Maven / Gradle / Ivy

There is a newer version: 0.22.2
Show newest version
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)




© 2015 - 2024 Weber Informatics LLC | Privacy Policy