Adam Hurwitz
Sep 4, 2018 · 1 min read

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

Written by

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade