【问题标题】:Dagger Hilt how to inject classes into ViewModelDagger Hilt 如何将类注入 ViewModel
【发布时间】:2021-01-11 21:08:45
【问题描述】:

我最近通过 Dagger Hilt 开始在我的项目中使用 DI。将实例注入活动、片段......等时我没有问题。但我不确定如何将类实例注入 ViewModel。

我目前的方法包括将我需要的类添加到视图模型的构造函数中:

class MainViewModel @ViewModelInject constructor(
application: Application,
@Named("classA") var classA: ClassA,
@Named("classB") var classB: ClassB
) : AndroidViewModel(application) 

然后在我的 AppModule 中:

@Module
@InstallIn(ApplicationComponent::class)
object AppModule {

@Singleton
@Provides
@Named("ClassA")
fun provideClassA(@ApplicationContext context: Context) = ClassA(context)

@Singleton
@Provides
@Named("ClassB")
fun provideClassB(@ApplicationContext context: Context) = ClassB(context)

}

效果很好,但理想情况下,如果我想添加更多其他类的实例,我更愿意这样做

@Inject
lateinit var classA:ClassA

但我认为这是不可能的,因为不可能将@AndroidEntryPoint 添加到 viewModel,那么如何将类注入到 viewmodel 中?还是我们只是将它们添加到构造函数中,就像我当前的解决方案一样?

【问题讨论】:

    标签: android kotlin dependency-injection dagger-hilt


    【解决方案1】:

    您只需将它们添加到构造函数中。在您的情况下,您甚至不需要@Named(),因为你们两个依赖项都提供了另​​一个类。所以:

    class YourViewModel @ViewModelInject(
       @ApplicationContext private val context: Context
       private val classA: ClassA, // or non-private, but it has to be a val
       private val classB: ClassB // or non-private, but it has to be a val
    ) : ViewModel()
    

    此外,您不需要在此处使用 AndroidViewModel。 Dagger 将通过@ApplicationContext private val context: Context 为您提供应用程序上下文。请注意,为了使用这个视图模型,片段和活动必须用@AndroidEntryPoint进行注释

    【讨论】:

    • 这给出了警告 This field leaks a context object 的上下文
    • @AbhishekAN 在 onDestroy() 方法中将泄漏原因设置为 null 以避免泄漏
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多