Adam Hurwitz
1 min readSep 4, 2018

--

Florina Muntenescu and Parag Kadam. I don’t know if the Architecture guides’ suggestion under Persist Data to use Dagger2 is the best strategy for an app built with Kotlin.

As @Ajay points out in his post Building database with Room Persistence Library a Singleton pattern can be used to create a Database which achieves the same result as Dagger2. I’ve heard Dagger2 has issues with Kotlin and might be more complicated to get up and running.

@Database(entities = arrayOf(Content::class), version = 1)
@TypeConverters(Converters::class)
abstract class ContentDatabase : RoomDatabase() {

abstract fun userDao(): ContentDao

companion object {

private var INSTANCE: ContentDatabase? = null

fun
getAppDatabase(context: Context): ContentDatabase {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.applicationContext,
ContentDatabase::class.java, "content-database")
.build()
}
return INSTANCE as ContentDatabase
}

fun destroyInstance() {
INSTANCE = null
}
}
}

--

--

Adam Hurwitz

An account about nothing | Researcher and product consultant