Hello! I want to repeat an operation until a cert...
# arrow
k
Hello! I want to repeat an operation until a certain condition is met. My API returns paged results and I want to collect all the results. Is there an idiomatic way to do this? Something similar to this "pseudo code"?
Copy code
data class Response(
    val page: Int,
    val perPage: Int,
    val items: List<Item>,
) {
    internal fun isAdditionalRequestNeeded(): Boolean =
        // Since we might have items on the next page.
        perPage == items.size 
}

fun getAllItems(api: Client): Either<Timeout, List<Item>> {
    val fetcher = { page: Int -> api.getItems(page) }
    return Either.catch { fetcher(1) }
        .mapLeft { Timeout }
        .reduceUntil(
            condition = { response: Response -> 
                // Repeat the `fetcher` call with incrementing page
                // until the `isAdditionalRequestNeeded` return false.
                !response.isAdditionalRequestNeeded()
            },
            block = { acc: List<Item>, response: Response ->
                acc.addAllItems(response.items)
                next(fetcher(response.page + 1))
            }
        )
}
c
1
thank you color 1
arrow intensifies 2
k
Yep, that worked, thank you!
🙌 1