mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-11-22 16:23:50 +00:00
one more time update mechanism of sql transactions in android
This commit is contained in:
parent
3de5558ed4
commit
615f7f99c3
@ -2,22 +2,26 @@ package dev.inmo.micro_utils.repos
|
||||
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import dev.inmo.micro_utils.coroutines.safely
|
||||
import kotlinx.coroutines.newSingleThreadContext
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.*
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.coroutines.CoroutineContext
|
||||
import kotlin.coroutines.coroutineContext
|
||||
|
||||
object InTransaction: CoroutineContext.Element, CoroutineContext.Key<InTransaction> {
|
||||
override val key: CoroutineContext.Key<InTransaction> = InTransaction
|
||||
class TransactionContext(
|
||||
val databaseContext: CoroutineContext
|
||||
): CoroutineContext.Element {
|
||||
override val key: CoroutineContext.Key<TransactionContext> = TransactionContext
|
||||
|
||||
companion object : CoroutineContext.Key<TransactionContext>
|
||||
}
|
||||
|
||||
suspend fun <T> SQLiteDatabase.transaction(block: suspend SQLiteDatabase.() -> T): T {
|
||||
return when {
|
||||
coroutineContext[InTransaction] == InTransaction -> {
|
||||
return coroutineContext[TransactionContext] ?.let {
|
||||
withContext(it.databaseContext) {
|
||||
block()
|
||||
}
|
||||
else -> {
|
||||
withContext(InTransaction) {
|
||||
} ?: Executors.newSingleThreadExecutor().asCoroutineDispatcher().let { context ->
|
||||
withContext(TransactionContext(context) + context) {
|
||||
beginTransaction()
|
||||
safely(
|
||||
{
|
||||
@ -32,7 +36,6 @@ suspend fun <T> SQLiteDatabase.transaction(block: suspend SQLiteDatabase.() -> T
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <T> SQLiteDatabase.inlineTransaction(block: SQLiteDatabase.() -> T): T {
|
||||
|
Loading…
Reference in New Issue
Block a user