Using room as singleton in kotlin

后端 未结 5 1248
被撕碎了的回忆
被撕碎了的回忆 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:05

    In this particular case I would resort to using Dagger 2, or some other dependency injection library like Koin or Toothpick. All three libraries allow to provide dependancies as singletons.

    Here's the code for Dagger 2 module:

    @Module
    class AppModule constructor(private val context: Context) {
        @Provides
        @Singleton
        fun providesDatabase(): AppDatabase {
            return Room.databaseBuilder(
                    context,
                    AppDatabase::class.java,
                    "train.db")
                    .build()
        }
    }
    

    AppComponent:

    @Singleton
    @Component(modules = arrayOf(
            AppModule::class
    ))
    interface AppComponent {
        fun inject(viewModel: YourViewModel)
        fun inject(repository: YourRepository)
    }
    

    Application class to provide injection:

    class App : Application() {
        companion object {
            private lateinit var appComponent: AppComponent
            val component: AppComponent get() = appComponent
        }
    
        override fun onCreate() {
            super.onCreate()
            initializeDagger()
        }
    
        private fun initializeDagger() {
            component = DaggerAppComponent.builder()
                    .appModule(AppModule(this))
                    .build()
        }
    }
    

    And then inject your database as singleton to wherever you need it (for example in your app's repository):

    @Inject lateinit var appDatabase: AppDatabase
    
    init {
        App.component.inject(this)
    }
    

提交回复
热议问题