簡體   English   中英

如何在 Room MVVM 架構中實現 Koin 依賴注入

[英]How to implement Koin dependency injection in Room MVVM Architecture

我正在按照這個文檔來實現 koin 依賴注入,但它對我沒有幫助。 我被困在Modules.kt文件中,我不知道如何將數據庫的 DAO 接口傳遞給 koin module中的Repository構造函數。

用戶實體.kt

@Entity(tableName = "user_table")
data class UserEntity(...)

用戶道.kt

@Dao
interface UserDao { ... }

用戶存儲庫.kt

class UserRepository(private val userDao: UserDao) {...}

用戶視圖模型.kt

class UserViewModel(private val repository: UserRepository) : ViewModel() {...}

用戶數據庫.kt

@Database(
    entities = [UserEntity::class],
    version = 1,
    exportSchema = false
)
abstract class UserDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {

        @Volatile
        private var INSTANCE: UserDatabase? = null
        fun getDatabase(context: Context, scope: CoroutineScope): UserDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    UserDatabase::class.java,
                    "user_data_database"
                ).build()
                INSTANCE = instance
                instance
            }
        }
    }
}

Modules.kt這是 Koin 模塊

val appModule = module{

    single { UserRepository(get()) }

    viewModel { UserViewModel(get()) }

}

首先,在從 Room Database 類擴展的類文件中。 您將需要創建一個抽象函數來提供這樣的 Dao 接口的實例,

@Database(entities = [Run::class],version = 1 , exportSchema = false)
abstract class RunningDatabase : RoomDatabase() {

abstract fun getRunDao(): RunDao
}

然后在您的模塊中為這樣的房間數據庫提供實例,

single {
   Room.databaseBuilder(
     androidApplication,
     RunningDatabase::class.java,
     RUNNING_DATABASE_NAME
 ).build()
}

現在可以調用 Room Database 類的抽象函數來獲取 Dao 接口的實例。 像這樣,

single<RunningDao> {
  val database = get<RunningDatabase>()
  database.getRunDao()
}

現在你可以在任何構造函數中傳遞這個接口。

在我的案例中,我只是在 Application class 中添加了 Koin 模塊,並讓數據庫將 DAO 接口傳遞給 koin 模塊中的 Repository 構造函數。 是完整的示例。

class MainApplication:Application() {

    private val applicationScope = CoroutineScope(SupervisorJob())
    private val database by lazy { UserDatabase.getDatabase(this,applicationScope) }


    override fun onCreate() {
        super.onCreate()
        startKoin{
            androidContext(this@MainApplication)
            modules(listOf(appModule))
        }
    }

    private val appModule = module{
        single { database.userDao() }

        single { UserRepository(get()) }

        single { UserViewModel(get()) }
   
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM