我最近开始通过Dagger-Hilt在我的项目中使用DI。在将实例注入Activities、fragments时,我没有遇到任何问题。。。等等。但我不知道如何将类实例注入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
但我认为这是不可能的,因为在viewModel中添加@AndroidEntryPoint是不可行的,那么类是如何注入到viewModel中的呢?还是像我当前的解决方案一样,将它们添加到构造函数中?
您只需将它们添加到构造函数中即可。在您的情况下,您甚至不需要@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
进行注释