https://kotlinlang.org logo
#android
Title
# android
j

Jérôme Gully

12/28/2019, 11:33 AM
Hi, I want to have my database and repository properties into my Application class. It's working but I wonder if this is okey and clean way of doing this ? Maybe i will use dagger in the future but not now.
Copy code
class MyApp : Application() {
    val database: AppDatabase by lazy { AppDatabase.getInstance(this) }
    val dataRepository: DataRepository by lazy { DataRepository(database.documentDao) }
}
👍 1
b

Brendan Weinstein

12/28/2019, 8:42 PM
I think this is a great way to expose singleton application scope without adding in a framework.
If the dependency is application scoped might be worth throwing it in MyApp companion object for ergonomics
j

Jérôme Gully

12/28/2019, 10:04 PM
Thanks for the advice 🙂, cleaner than before
But for the database I use
this
, how can I pass application instance (for context) in the companion object ?
b

Brendan Weinstein

12/28/2019, 10:10 PM
Copy code
class App : Application {
  companion object {
    lateinit var appInstance: App

    val dateabase: AppDatabase by lazy { AppDatabase.getInstance(appInstance) }
  }

  onCreate {
    appInstance = this
  }
}
j

Jérôme Gully

12/28/2019, 10:11 PM
Thanks 🙂
👍 1