简体   繁体   English

Dagger Hilt 如何将类注入 ViewModel

[英]Dagger Hilt how to inject classes into ViewModel

I recently started using DI in my project through Dagger Hilt.我最近开始通过 Dagger Hilt 在我的项目中使用 DI。 I'm having no problems when injecting instances into Activities, fragments... etc. But I am not sure how to inject a class instance into ViewModel.将实例注入活动、片段......等时我没有问题。但我不确定如何将 class 实例注入 ViewModel。

My approach at the moment consists of adding the classes I need to the constructor of the viewmodel as such:我目前的方法包括将我需要的类添加到视图模型的构造函数中:

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

and then in my AppModule:然后在我的 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)

}

Which works great, but ideally and in the case I wanted to add many more instances of other classes, I would prefer doing效果很好,但理想情况下,如果我想添加更多其他类的实例,我宁愿这样做

@Inject
lateinit var classA:ClassA

But I presume this is not possible, as adding @AndroidEntryPoint to the viewModel is not possible, so how are classes injected into viewmodel?但我认为这是不可能的,因为不可能将 @AndroidEntryPoint 添加到 viewModel 中,那么如何将类注入到 viewmodel 中? or do we just add them to constructor, as in my current solution?还是我们只是将它们添加到构造函数中,就像我当前的解决方案一样?

You just add them to the constructor.您只需将它们添加到构造函数中。 And in your case, you don't even need @Named() because both of you dependencies provide another class.在您的情况下,您甚至不需要@Named()因为你们两个依赖项都提供了另一个 class。 So:所以:

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()

Furthermore, you don't need to use AndroidViewModel here.此外,您不需要在此处使用 AndroidViewModel。 Dagger will provide you the application context via @ApplicationContext private val context: Context . Dagger 将通过@ApplicationContext private val context: Context为您提供应用程序上下文。 Be aware that in order to use this viewmodel, the fragment and activity has to be annotated with @AndroidEntryPoint请注意,为了使用此视图模型,必须使用@AndroidEntryPoint注释片段和活动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM