天天看點

android SQLite事務和kotlin協程

SQLite事務和Kotlin協程結合使用需要特别特别注意

suspend fun test(bsc:BookSourceConfig){
        val db = DBManager.openDatabaseW()
        if (db != null) {
            db.beginTransaction()
            try {
                testA(db,bsc)
                testB(db, bsc)
                db.setTransactionSuccessful()
            } finally {
                db.endTransaction()
            }
        }
    }
           

當testA和testB不在同一線程執行時setTransactionSuccessful和endTransaction都不能被執行。測試為了每次TestA和TestB都是在不同線程執行,在testA 重使用async,如下

private suspend fun testA(db: SQLiteDatabase,bsc:BookSourceConfig) = withContext(Dispatchers.IO){
        async {
        val whereClause = "${BookSourceConfigSchema.KEY_KEY} = ?"
        val whereArgs = arrayOf(bsc.id.toString())
        val num = db.delete(BookSourceConfigSchema.TABLE_NAME, whereClause, whereArgs) > 0
        }
    }
           
private suspend fun testB(db: SQLiteDatabase,bsc:BookSourceConfig) = withContext(Dispatchers.IO){
        val values = getContentValues(bsc)
        var num = db.insert(BookSourceConfigSchema.TABLE_NAME, null, values).toInt()
    }
           

這樣每次都會出 如下錯誤:

W/SQLiteConnectionPool: The connection pool for database ‘/data/data/xxx.xx.xx/databases/xxxx’ has been unable to grant a connection to thread 2107 (DefaultDispatcher-worker-4) with flags 0x2 for 540.01105 seconds. Connections: 0 active, 1 idle, 0 available.

原因如下圖

圖檔來自# Kotlin 協程和 Android SQLite API 中的線程模型

android SQLite事務和kotlin協程

切記切記 事務中不要有協程挂起