1 package leakcanary.internal.activity.db 2 3 import android.database.sqlite.SQLiteDatabase 4 import android.view.View 5 import leakcanary.internal.activity.db.Db.OnDb 6 import leakcanary.internal.activity.db.Io.OnIo 7 import leakcanary.internal.activity.db.ScopedLeaksDb.DbOpener 8 9 internal object Db { 10 11 // Accessed on the IO thread only. 12 private var dbHelper: DbOpener? = null 13 14 interface OnDb : OnIo { 15 val db: SQLiteDatabase 16 } 17 18 private class DbContext(override val db: SQLiteDatabase) : OnDb { 19 var updateUi: (View.() -> Unit)? = null 20 updateUinull21 override fun updateUi(updateUi: View.() -> Unit) { 22 this.updateUi = updateUi 23 } 24 } 25 executenull26 fun execute( 27 view: View, 28 block: OnDb.() -> Unit 29 ) { 30 val appContext = view.context.applicationContext 31 Io.execute(view) { 32 if (dbHelper == null) { 33 dbHelper = ScopedLeaksDb.open(appContext) 34 } 35 val dbBlock = DbContext(dbHelper!!.writableDatabase) 36 block(dbBlock) 37 val updateUi = dbBlock.updateUi 38 if (updateUi != null) { 39 updateUi(updateUi) 40 } 41 } 42 } 43 closeDatabasenull44 fun closeDatabase() { 45 // Closing on the serial IO thread to ensure we don't close while using the db. 46 Io.execute { 47 dbHelper?.close() 48 dbHelper = null 49 } 50 } 51 } 52 executeOnDbnull53internal fun View.executeOnDb(block: OnDb.() -> Unit) { 54 Db.execute(this, block) 55 } 56