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

waltermcq

04/19/2020, 12:25 PM
Question on ktor + exposed + coroutines
I'm trying to insert a new user into my database using the exposed DSL, with transactions that are wrapped with coroutines e.g. the dqQuery {} method frequently found for this purpose
Here's basically what the insert function is:
Copy code
override suspend fun newUser(id: String, name: String): UserAgg {
        return dbQuery {
            val userRow = UserTable.insert {
                it[this.id] = id
                it[this.name] = name
            }.resultedValues!!.first()

          getUserById(UserId(userRow[UserTable.id]))!!
        }
    }
Heres's dbQuery()
Copy code
suspend fun <T> dbQuery(
    block: () -> T): T =
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        transaction { block() }
    }
The issue is in the newUser function, when I call getUserById to get the new id (specifically, a uuid) from the database after the insert, intellij tells me that getUserById must be called within a coroutine body I can't wrap getUserById in a dbQuery() call inside newUser, I get the same issue (as its apparently not a coroutine body) (edited)  what is the best way to call getUserById() given the need for a coroutine body?
l

louiscad

04/19/2020, 12:51 PM
The
block
lambda of the
dbQuery
function is not suspending, that's why.
w

waltermcq

04/19/2020, 3:12 PM
@louiscad okay, what would be the proper way to make the
block
lambda suspending?
I am quite new to both kotlin and working with coroutines, thanks for your patience
l

louiscad

04/19/2020, 3:31 PM
@waltermcq Adding
suspend
as a prefix in the type of
block
, if
transaction
takes a suspending lambda. Otherwise, you'll need to slip your code to do it in two steps so there's no suspend call in the transaction.
w

waltermcq

04/19/2020, 3:32 PM
okay, I did add the suspend to the type of block, but then the block() call itself requires a coroutine body
I think I am a bit over my head here, so I'm going to go do some reading
anyway, thanks for your help @louiscad
15 Views