I have a database DAO from which I want to return ...
# coroutines
r
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
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