How to use Sqldelight with Kotlin Coroutines
Asked Answered
M

2

8

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?

Merkle answered 23/2, 2020 at 6:59 Comment(0)
M
11

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.

Merkle answered 23/2, 2020 at 6:59 Comment(4)
Addition to this excellent answer for multiplatform projects: add dependency in commonMain and use latest lib version (which is 1.3.0 currently) commonMain.dependencies { implementation ....}Thrasher
Official documentation: cashapp.github.io/sqldelight/multiplatform_sqlite/coroutinesThrasher
Without suspend function support, doesn't it mean that all queries are blocking? It seems the other answer (https://mcmap.net/q/1256646/-how-to-use-sqldelight-with-kotlin-coroutines) is the good one.Allysonalma
What is the exact package of asFlow() extension method?Cero
M
9

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.

Mutant answered 1/2, 2021 at 6:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.