[英]Android Hilt dagger inject interface in viewModel @ViewModelInject got UninitializedPropertyAccessException
[英]Inject FragmentComponent dependencies to viewmodel with @ViewModelInject
我想在FragmentComponent
依賴項中使用我的ViewModel
片段,但我認為@ViewModelInject
在ActivityComponent
或ApplicationCoinmponent
內提供 ViewModel 並且不能將我的FragmentComponent
依賴項注入到ViewModel
class XViewModel @ViewModelInject constructor(
private val xClass: XClass // this dependency provides in FragmentComponent
) : ViewModel() {
}
當我嘗試構建項目時。 構建失敗並出現KaptException
並且刀柄編譯器說我不能提供XClass
。 XClass
在FragmentComonent
提供。 當我將XClass
提供程序方法移動到ActivityComponent
或ApplicationComponent
構建不再因KaptException
失敗。
編輯:我閱讀了 Hilt 生成的代碼,我的猜測是正確的, Hilt 和@ViewModelInject
在ActivityRetainedComponent
安裝XViewModel
模塊。 我不知道為什么?
@Module
@InstallIn(ActivityRetainedComponent.class)
@OriginatingElement(
topLevelClass = XViewModel.class
)
public interface XViewModel_HiltModule
我在這里找到了答案。 hilt 團隊這樣做是因為從片段組件注入東西可能會在配置更改時泄漏 Fragment 實例。 ActivityRetainedComponent
存在於配置更改中,因此它在第一次 onCreate 和最后一次 onDestroy 時創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.