개발일지

Android in A..Z - Room (allowMainThreadQueries) 본문

Android (안드로이드)/Room

Android in A..Z - Room (allowMainThreadQueries)

강태종 2021. 1. 17. 03:25

allowMainThreadQueries

Room에서 기본적으로 Main Thread에서 접근할 수 없지만, allowMainThreadQueries를 사용하여 만든 Instance에서는 Main Thread에서도 접근할 수 있다. 

=> Database를 접근하는 작업은 무거운 작업이고 UI를 오랫동안 잠글 수 있기 Main Thread에서 접근하는 것은 좋지 않다.


AppDatabase

package com.taetae98.room.singleton

import android.content.Context
import androidx.room.CoroutinesRoom
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.taetae98.room.DATABASE_NAME
import com.taetae98.room.data.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Database(entities = [Drawer::class, ToDo::class], version = 2, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
    companion object {
        private var instance: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase {
            return instance ?: synchronized(this) {
                Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
                    .addCallback(object : Callback() {
                        override fun onCreate(db: SupportSQLiteDatabase) {
                            super.onCreate(db)
                            CoroutineScope(Dispatchers.IO).launch {
                                getInstance(context).drawer().insert(
                                    Drawer(name = "ToDo")
                                )
                            }
                        }
                    })
                    .addMigrations(MIGRATION_1_2)
//                    .allowMainThreadQueries()
                    .build()
            }.also {
                instance = it
            }
        }

        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE ToDo ADD COLUMN isFinished INTEGER DEFAULT 0 NOT NULL")
            }
        }
    }

    abstract fun drawer(): DrawerDao
    abstract fun todo(): ToDoDao
}

Git (예제코드)

github.com/KangTaeJong98/Example/tree/main/Android/Room

 

KangTaeJong98/Example

My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.

github.com

 

Comments