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

rocketraman

10/23/2018, 5:12 PM
I have a database DAO from which I want to return a
Sequence
. However, I also want to close the db cursor when the sequence has finished consuming. Is this a valid approach?
Copy code
suspend fun findSomethings(...): Sequence<Something> {
  val cursor = ...
  return sequence {
    cursor.use {
      yieldAll(cursor.iterator())
    }
  }
}
d

Dominaezzz

10/23/2018, 7:36 PM
I would not use that approach. Mainly because if the user of the returned
Sequence
does not fully iterate through it, your cursor will not be closed.
Also, since there is no way to "close" an
Iterable
or
Sequence
, you shouldn't tie the lifetime of a resource to one.
So I would suggest returning a
List<Something>
or (depending on your use case) maybe a
ReceiveChannel
since that can be "close"d.
👍 1
3 Views