kotlinforandroid
01/03/2024, 10:47 PMdata 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))
}
)
}
CLOVIS
01/04/2024, 10:55 AMkotlinforandroid
01/04/2024, 11:32 AM