Jacques.S
Jacques.S

Reputation: 3593

How to use Sqldelight with Kotlin Coroutines

There are apparently Kotlin coroutines extension functions for SqlDelight, but I don't know how to implement them since I can't find documentation.

I have a normal query that looks like this:

val allItems
  get() = itemQueries.selectAll().mapToList()

Can I turn this into a suspend function?

Upvotes: 8

Views: 6307

Answers (3)

frevib
frevib

Reputation: 453

Using @marks answer with Java Virtual Threads to make it really non-blocking:

private val vtDispatcher = Executors.newVirtualThreadPerTaskExecutor().asCoroutineDispatcher()

suspend fun getAllItems() = withContext(vtDispatcher) {
    itemQueries.selectAll().mapToList()
}

Upvotes: 0

Mark
Mark

Reputation: 7718

For single-shot queries, you don't need the coroutine extension library. Instead, just do:

suspend fun getAllItems() = withContext(Dispatchers.IO) {
    itemQueries.selectAll().mapToList()
}

The other answer is specific to when you want to react to changes in the database.

Upvotes: 10

Jacques.S
Jacques.S

Reputation: 3593

There is currently (v1.2.1) no suspend function support for SqlDelight queries, however you can consume a Coroutines Flow object, which is even better. To do this you need to add the coroutines extension library in your app gradle:

dependencies {
  implementation "com.squareup.sqldelight:coroutines-extensions:1.2.1"
}

Then turn your query into this:

val allItems: Flow<List<Item>> = 
  itemQueries.selectAll()
    .asFlow()
    .mapToList()

This flow emits the query result, and emits a new result every time the database changes for that query.

You can then .collect{} the results inside a coroutine scope.

Upvotes: 11

Related Questions