Using room as singleton in kotlin

后端 未结 5 1245
被撕碎了的回忆
被撕碎了的回忆 2021-02-01 08:24

I\'m trying to use Room as singleton so I didn\'t have to invoke Room.databaseBuilder() -which is expensive- more than once.

@Database(entities = ar         


        
5条回答
  •  难免孤独
    2021-02-01 09:13

    Here's how i figured out...

    @Database(entities = [MyEntity::class], version = dbVersion, exportSchema = true)
    abstract class AppDB : RoomDatabase() {
    
    // First create a companion object with getInstance method
        companion object {
            fun getInstance(context: Context): AppDB = 
        Room.databaseBuilder(context.applicationContext, AppDB::class.java, dbName).build()
        }
    
        abstract fun getMyEntityDao(): MyEntityDao
    }
    
    // This is the Singleton class that holds the AppDB instance 
    // which make the AppDB singleton indirectly
    // Get the AppDB instance via AppDBProvider through out the app
    object AppDBProvider {
    
    private var AppDB: AppDB? = null
    
        fun getInstance(context: Context): AppDB {
            if (appDB == null) {
                appDB = AppDB.getInstance(context)
            }
           return appDB!!
        }
    
    }
    

提交回复
热议问题