How do you “close” a flow? I’m trying to wrap a pa...
# coroutines
s
How do you “close” a flow? I’m trying to wrap a paginated API call, with ktor, into a flow. I want the flow to emit all pages, and stop emitting once I’ve queried the last page.
z
cancel the scope it’s launched with
s
So this would work?
Copy code
flow {
    emit(page)
    if(page.isLast) {
       cancel()
    }
}
z
If you’re using the
flow
builder (or
callback/channelFlow
), just return from the lambda. You don’t need to cancel.
👍 3
z
once the
flow { .. }
lambda completes, the flow cancels automatically
s
Oh yeah I forgot about that. I guess I need a repeat in there.
Is there sugar for a while loop that also counts the number of iterations? Not coroutine related but is related my original question
z
Not on a raw
while
loop, but a lot of the iterable/sequence operators have a
WithIndex
or
Indexed
version that does.
👍 1