Skip to content

Instantly share code, notes, and snippets.

@novotnyr
Created March 15, 2021 07:36
Show Gist options
  • Save novotnyr/50fa8d2efd2c609b0ae8fbdc0bd0bb21 to your computer and use it in GitHub Desktop.
Save novotnyr/50fa8d2efd2c609b0ae8fbdc0bd0bb21 to your computer and use it in GitHub Desktop.
package com.github.novotnyr.yello
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [Note::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDao
companion object {
@Volatile
private var db: AppDatabase? = null
operator fun invoke(context: Context): AppDatabase =
db ?: synchronized(this) {
db ?: context.buildDatabase()
.also {
db = it
}
}
private fun Context.buildDatabase(): AppDatabase {
return Room.databaseBuilder(
applicationContext,
AppDatabase::class.java,
"note-database"
).build()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment