[英]Android Hilt dagger inject interface in viewModel @ViewModelInject got UninitializedPropertyAccessException
我嘗試使用 Hiltcodelab https://codelabs.developers.google.com/codelabs/android-hilt#10
它與 Activity 和 Fragment 配合得很好
記錄器是一個 RoomDB
然后我嘗試用這篇文章將記錄器注入viewModel
通過添加
implementation "androidx.hilt:hilt-lifecycle-viewmodel
:1.0.0-alpha02"
kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha02'
查看模型代碼
class RecordFragmentViewModel @ViewModelInject constructor(@Assisted private val savedStateHandle: SavedStateHandle) :
ViewModel() {
@DatabaseLogger
@Inject
lateinit var logger: LoggerDataSource
Class 記錄器注入
class LoggerLocalDataSource
@Inject constructor(private val logDao: LogDao) : LoggerDataSource {
記錄模塊
@Qualifier
annotation class InMemoryLogger
@Qualifier
annotation class DatabaseLogger
@InstallIn(ApplicationComponent::class)
@Module
abstract class LoggingDatabaseModule {
@DatabaseLogger
@Singleton
@Binds
abstract fun bindDatabaseLogger(impl: LoggerLocalDataSource): LoggerDataSource
}
@InstallIn(ActivityComponent::class)
@Module
abstract class LoggingInMemoryModule {
@InMemoryLogger
@ActivityScoped
@Binds
abstract fun bindInMemoryLogger(impl: LoggerInMemoryDataSource): LoggerDataSource
}
數據庫模塊
@InstallIn(ApplicationComponent::class)
@Module
object DatabaseModule {
@Provides
@Singleton
fun provideDatabase(@ApplicationContext appContext: Context): AppDatabase {
return Room.databaseBuilder(
appContext,
AppDatabase::class.java,
"logging.db"
).build()
}
@Provides
fun provideLogDao(database: AppDatabase): LogDao {
return database.logDao()
}
}
它的編譯和運行沒有錯誤。 但是,我使用調試來觀察記錄器及其得到的。
Method threw 'kotlin.UninitializedPropertyAccessException' exception.
我在運行時調用 logger.something() 它的拋出
Fatal Exception: kotlin.UninitializedPropertyAccessException
lateinit property logger has not been initialized
更多信息https://dagger.dev/hilt/migration-guide.html
https://codelabs.developers.google.com/codelabs/android-hilt#10
由於 LoggerDataSource 是一個接口,我們需要指定我們需要注入的實現。 感謝@Andrew 提供注入構造函數的想法
class RecordFragmentViewModel
@ViewModelInject
constructor(@Assisted private val savedStateHandle: SavedStateHandle,
@DatabaseLogger private val logger: LoggerDataSource) :
ViewModel(), LifecycleObserver {
指定
@Qualifier
annotation class InMemoryLogger
@Qualifier
annotation class DatabaseLogger
@InstallIn(ApplicationComponent::class)
@Module
abstract class LoggingDatabaseModule {
@DatabaseLogger
@Singleton
@Binds
abstract fun bindDatabaseLogger(impl: LoggerLocalDataSource): LoggerDataSource
}
@InstallIn(ActivityComponent::class)
@Module
abstract class LoggingInMemoryModule {
@InMemoryLogger
@ActivityScoped
@Binds
abstract fun bindInMemoryLogger(impl: LoggerInMemoryDataSource): LoggerDataSource
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.