【问题标题】:Android - Dagger inject Shared ViewModel to FragmentAndroid - Dagger 将 Shared ViewModel 注入到 Fragment
【发布时间】:2021-02-23 23:46:27
【问题描述】:

我需要用共享的 ViewModel 绑定两个片段。

组件:

void injectMovieFragment(MovieFragment movieFragment);
void injectMovieCollectionFragment(MovieCollectionFragment movieCollectionFragment);  

SharedViewModelModule:

@Provides
MovieSharedViewModel provideMovieSharedViewModel(Fragment fragment) {

    return new ViewModelProvider(fragment.requireActivity()).get(MovieSharedViewModel.class);

}  

此代码导致 Dagger 上出现 MissingBinding 错误(无法从 MovieFragment/MovieCollectionFragment 获取 Fragment)。

SharedViewModelModule v2:

@Provides
MovieSharedViewModel provideMovieSharedViewModelToMovieFragment(MovieFragment fragment) {

    return new ViewModelProvider(fragment.requireActivity()).get(MovieSharedViewModel.class);

}

@Provides
MovieSharedViewModel provideMovieSharedViewModelToMovieCollectionFragment(MovieCollectionFragment fragment) {

    return new ViewModelProvider(fragment.requireActivity()).get(MovieSharedViewModel.class);

}  

此代码导致 Dagger 上出现 DuplicateBindings 错误。

要在没有 Dagger2 注入的情况下获得 sharedViewModel,我只是使用:

sharedViewModel = new ViewModelProvider(requireActivity()).get(MovieSharedViewModel.class);  

在 MovieFragment 和 MovieCollectionFragment 类的 onViewCreated 中,这很好用。
如何使用 Dagger 2 正确注入此共享 ViewModel?

【问题讨论】:

    标签: android android-fragments mvvm viewmodel dagger-2


    【解决方案1】:

    如果您可以在片段中添加如何使用注入,那就太好了。从错误来看,您似乎没有将创建的片段注入您的匕首图中。

    这是必需的,因为片段通常由 android 创建,您需要将创建的实例提供给 dagger。

    我以前这样做的方式就像从我的CustomApplication 类中公开我的DaggerComponent(您也可以通过您的活动公开该组件)。 然后在片段的onAttach 函数中像这样注入创建的片段。

    override fun onAttach(context: Context) {
            super.onAttach(context)
            (context.applicationContext as CustomApplication).applicationComponent.injectMovieFragment(this)
    }
    

    这应该可以修复错误。请提供您如何在片段中使用注入以获得更完整的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 2018-12-08
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多