one more time update mechanism of sql transactions in android

This commit is contained in:
InsanusMokrassar 2020-11-22 22:00:50 +06:00
parent 3de5558ed4
commit 615f7f99c3

View File

@ -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(
{
@ -33,7 +37,6 @@ suspend fun <T> SQLiteDatabase.transaction(block: suspend SQLiteDatabase.() -> T
}
}
}
}
inline fun <T> SQLiteDatabase.inlineTransaction(block: SQLiteDatabase.() -> T): T {
return when {