Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- Algorithm
- Android
- onLayout
- Behavior
- CoordinatorLayout
- BOJ
- onMeasure
- View
- 코틀린
- 안드로이드
- Navigation
- ViewModel
- sqlite
- LiveData
- 알림
- AppBarLayout
- 알고리즘
- notification
- lifecycle
- CustomView
- DataBinding
- Coroutine
- room
- CollapsingToolbarLayout
- 백준
- activity
- kotlin
- hilt
- HTTP
- recyclerview
Archives
- Today
- Total
개발일지
Android in A..Z - Room (allowMainThreadQueries) 본문
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
'Android (안드로이드) > Room' 카테고리의 다른 글
Android in A..Z - Room (Minimal) (0) | 2021.01.17 |
---|---|
Android in A..Z - Room (TypeConvert) (1) | 2021.01.17 |
Android in A..Z - Room (관계) (0) | 2021.01.17 |
Android in A..Z - Room (Migration) (0) | 2021.01.17 |
Android in A..Z - Room (데이터 미리 채우기) (0) | 2021.01.17 |
Comments