Dagger Hilt 如何将 类 注入 ViewModel
Dagger Hilt how to inject classes into ViewModel
我最近开始通过 Dagger Hilt 在我的项目中使用 DI。我在将实例注入 Activities、片段等时没有遇到任何问题。但我不确定如何将 class 实例注入 ViewModel。
我目前的方法包括将我需要的 classes 添加到视图模型的构造函数中:
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)
}
效果很好,但理想情况下,如果我想添加更多其他 classes 的实例,我更愿意做
@Inject
lateinit var classA:ClassA
但我认为这是不可能的,因为将@AndroidEntryPoint 添加到 viewModel 是不可能的,那么 classes 是如何注入到 viewmodel 中的呢?或者我们只是将它们添加到构造函数中,就像我当前的解决方案一样?
您只需将它们添加到构造函数中即可。在您的情况下,您甚至不需要 @Named()
,因为你们两个依赖项都提供了另一个 class。所以:
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
为您提供应用程序上下文。请注意,为了使用此视图模型,片段和 activity 必须使用 @AndroidEntryPoint
进行注释
我最近开始通过 Dagger Hilt 在我的项目中使用 DI。我在将实例注入 Activities、片段等时没有遇到任何问题。但我不确定如何将 class 实例注入 ViewModel。
我目前的方法包括将我需要的 classes 添加到视图模型的构造函数中:
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)
}
效果很好,但理想情况下,如果我想添加更多其他 classes 的实例,我更愿意做
@Inject
lateinit var classA:ClassA
但我认为这是不可能的,因为将@AndroidEntryPoint 添加到 viewModel 是不可能的,那么 classes 是如何注入到 viewmodel 中的呢?或者我们只是将它们添加到构造函数中,就像我当前的解决方案一样?
您只需将它们添加到构造函数中即可。在您的情况下,您甚至不需要 @Named()
,因为你们两个依赖项都提供了另一个 class。所以:
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
为您提供应用程序上下文。请注意,为了使用此视图模型,片段和 activity 必须使用 @AndroidEntryPoint