Renan Kummer
09/27/2024, 3:06 AMtransaction
and newSuspendedTransaction
functions, so far in my app I've used newSuspendedTransaction
. However, I have a scenario where I'll need to call a set of functions that each interact with the database using newSuspendedTransaction
, and if something goes wrong, I'd like the whole set to be rolled back instead of just the transaction that went wrong. The issue doesn't happen if I use transaction
, but then I'm afraid I won't use Ktor appropriately since coroutines won't be used at all and the thread will be blocked until all the queries are done.
Any suggestions?Renan Kummer
09/27/2024, 3:30 AMwithSuspendedTransaction
reuses the parent transaction. Did I get this right?Renan Kummer
09/27/2024, 3:39 AMprivate suspend fun onSuspendedTransaction(f: suspend Transaction.() -> Unit) {
val currentTransaction = TransactionManager.currentOrNull()
if (currentTransaction == null) {
newSuspendedTransaction(Dispatchers.IO) { f() }
} else {
currentTransaction.withSuspendTransaction(Dispatchers.IO) { f() }
}
}
My test:
try {
onSuspendedTransaction {
onSuspendedTransaction {
items2.forEach {
insertGame(it) }
}
items1.forEach {
insertGame(it)
}
onSuspendedTransaction {
items3.forEach {
insertGame(it)
}
throw Exception()
}
}
} catch (_: Exception) {}