How to use Sqldelight with Kotlin Coroutines

Viewed 2252

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?

2 Answers

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.

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.

Related