簡體   English   中英

使用 @ViewModelInject 將 FragmentComponent 依賴項注入到視圖模型

[英]Inject FragmentComponent dependencies to viewmodel with @ViewModelInject

我想在FragmentComponent依賴項中使用我的ViewModel片段,但我認為@ViewModelInjectActivityComponentApplicationCoinmponent內提供 ViewModel 並且不能將我的FragmentComponent依賴項注入到ViewModel

class XViewModel @ViewModelInject constructor(
    private val xClass: XClass // this dependency provides in FragmentComponent
) : ViewModel() {

}

當我嘗試構建項目時。 構建失敗並出現KaptException並且刀柄編譯器說我不能提供XClass XClassFragmentComonent提供。 當我將XClass提供程序方法移動到ActivityComponentApplicationComponent構建不再因KaptException失敗。

編輯:我閱讀了 Hilt 生成的代碼,我的猜測是正確的, Hilt 和@ViewModelInjectActivityRetainedComponent安裝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.

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