mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-11-23 02:28:47 +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 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(
|
||||||
{
|
{
|
||||||
@ -32,7 +36,6 @@ suspend fun <T> SQLiteDatabase.transaction(block: suspend SQLiteDatabase.() -> T
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline fun <T> SQLiteDatabase.inlineTransaction(block: SQLiteDatabase.() -> T): T {
|
inline fun <T> SQLiteDatabase.inlineTransaction(block: SQLiteDatabase.() -> T): T {
|
||||||
|
Loading…
Reference in New Issue
Block a user