how do I make this work with a suspending function...
# getting-started
b
how do I make this work with a suspending function
Copy code
suspend fun <T> Pagination.paginate(
    fetchPage: suspend (page: String, size: String, sort: String?) -> List<T>,
): Sequence<T> {
    val sorted = sort
        .joinToString(",") { it.serialize() }
        .takeIf { it.isNotBlank() }
    val pageSize = pageSize
    return generateSequence(pageNumber) { i -> i + 1 }
        .map { page -> fetchPage(page.toString(), pageSize.toString(), sorted) }
        .takeWhile { it.isNotEmpty() }
        .flatMap { it.asSequence() }
}
fetchPage needs to be inside of a suspending function and it looks like generateSequence does not provide an inline map method
✅ 1
y
Just use a Flow instead of a Sequence.
b
thanks
y
Copy code
flow {
  var i = pageNumber
  while (true) emit(i++)
}
.map { ... }
.takeWhile { ... }
.flatMapConcat { it.asFlow() }
But I'd write it as:
Copy code
flow {
  var page = pageNumber
  while (true) {
    val pageResult = fetchPage(page++.toString(), pageSize.toString(), sorted)
    if (pageResult.isEmpty()) break
    emitAll(pageResult)
  }
}
b
is it possible to back to a sequence?
probably also needs emitAll(pageResult.asFlow())
y
Sadly no, but Flow really is the
suspend
equivalent of a Sequence. Think about the semantics you want here. Obviously, you want
fetchPage
to be called lazily whenever the results are needed.
fetchPage
is
suspend
, so your return type needs to require the consumer to
suspend
while
fetchPage
is running. Well, that's exactly what a
Flow
does! In other words,
fetchPage
being
suspend
necessitates using a
Flow
b
I suppose I would call collect or forEach on it anyways
💯 1
thank you, it's kinda funny that I was watching roman's flow talk in the background
wasn't able to piece it together though