Use `buildSequence`
# getting-started
d
Use
buildSequence
p
right but thats scary coroutines right
😱 2
d
Coroutines are great! 😄
It's in the stdlib, too
Then you can just write a for loop and
yield
p
ok so lets say i have code like this
a
it’s no longer experimental? 😉
p
Copy code
var offset = 0
val items = mutableListOf<Map<*, *>>()
while (true) {
    val chunk = queryRunner.query("SELECT id FROM item LIMIT 10000 OFFSET $offset")
    if (chunk.isEmpty()) {
        break
    }
    items.addAll(chunk)
    offset += 10000
    println("Loaded $offset rows")
}
and i would like to rewrite is as sequence
e
@arekolek no, they're
1.0.0
as soon as Kotlin 1.3 is released
m
buildSequence
has been renamed
sequence
in 1.3 by the way
a
with a local variable, this should do:
Copy code
var offset = 0
return generateSequence {
    queryRunner.query("SELECT id FROM item LIMIT 10000 OFFSET $offset")
            .takeUnless { it.isEmpty() }
            .also { offset += 10000 }
}
        .flatten()
p
thanks
a
Here’s a way without the variable and without pair:
Copy code
generateSequence(0) { it + 10000 }
        .map { queryRunner.query("SELECT id FROM item LIMIT 10000 OFFSET $it") }
        .takeWhile { it.isNotEmpty() }
        .flatten()