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,33 +2,36 @@ package dev.inmo.micro_utils.repos
|
|||||||
|
|
||||||
import android.database.sqlite.SQLiteDatabase
|
import android.database.sqlite.SQLiteDatabase
|
||||||
import dev.inmo.micro_utils.coroutines.safely
|
import dev.inmo.micro_utils.coroutines.safely
|
||||||
import kotlinx.coroutines.newSingleThreadContext
|
import kotlinx.coroutines.*
|
||||||
import kotlinx.coroutines.withContext
|
import java.util.concurrent.Executors
|
||||||
import kotlin.coroutines.CoroutineContext
|
import kotlin.coroutines.CoroutineContext
|
||||||
import kotlin.coroutines.coroutineContext
|
import kotlin.coroutines.coroutineContext
|
||||||
|
|
||||||
object InTransaction: CoroutineContext.Element, CoroutineContext.Key<InTransaction> {
|
class TransactionContext(
|
||||||
override val key: CoroutineContext.Key<InTransaction> = InTransaction
|
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 {
|
suspend fun <T> SQLiteDatabase.transaction(block: suspend SQLiteDatabase.() -> T): T {
|
||||||
return when {
|
return coroutineContext[TransactionContext] ?.let {
|
||||||
coroutineContext[InTransaction] == InTransaction -> {
|
withContext(it.databaseContext) {
|
||||||
block()
|
block()
|
||||||
}
|
}
|
||||||
else -> {
|
} ?: Executors.newSingleThreadExecutor().asCoroutineDispatcher().let { context ->
|
||||||
withContext(InTransaction) {
|
withContext(TransactionContext(context) + context) {
|
||||||
beginTransaction()
|
beginTransaction()
|
||||||
safely(
|
safely(
|
||||||
{
|
{
|
||||||
endTransaction()
|
endTransaction()
|
||||||
throw it
|
throw it
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
block().also {
|
block().also {
|
||||||
setTransactionSuccessful()
|
setTransactionSuccessful()
|
||||||
endTransaction()
|
endTransaction()
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user