https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Sam Garfinkel

05/28/2020, 8:45 PM
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

zak.taccardi

05/28/2020, 8:45 PM
cancel the scope it’s launched with
s

Sam Garfinkel

05/28/2020, 8:46 PM
So this would work?
Copy code
flow {
    emit(page)
    if(page.isLast) {
       cancel()
    }
}
z

Zach Klippenstein (he/him) [MOD]

05/28/2020, 8:46 PM
If you’re using the
flow
builder (or
callback/channelFlow
), just return from the lambda. You don’t need to cancel.
👍 3
z

zak.taccardi

05/28/2020, 8:47 PM
once the
flow { .. }
lambda completes, the flow cancels automatically
s

Sam Garfinkel

05/28/2020, 8:47 PM
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

Zach Klippenstein (he/him) [MOD]

05/28/2020, 9:04 PM
Not on a raw
while
loop, but a lot of the iterable/sequence operators have a
WithIndex
or
Indexed
version that does.
👍 1
2 Views