您好,我想在我的 BaseActivity 中注入(inject)通用 ViewModel 类型,如何使用 Dagger Hilt 解决这个问题。
@AndroidEntryPoint
abstract class BaseActivity<VM: BaseViewModel> : AppCompatActivity() {
@Inject
lateinit var viewModel: VM
}
最佳答案
更新 1
这是我正在谈论的 Hilt 团队的回复:
So @ViewModelInject is kind of a one way thing, similar to @AndroidEntryPoint in a way. It only gets Dagger dependencies into your class. It does not add your ViewModel to the object graph as a Dagger binding. In order to access your ViewModel in a provider or somewhere else, you still need to go through the normal Android APIs of getting a view model like using a ViewModelProvider.
The reason we can't provide it into the graph is that we don't know what ViewModelStoreOwner you want to use it with.
您可以找到此评论here。
原始答案
几天前我试图这样做,我想我在互联网上的某个地方读到了希尔特不可能做到这一点(到目前为止我找不到链接)。
通常在 Java 中我们创建 ViewModel 如下:
MyViewModel model = new ViewModelProvider(this).get(MyViewModel.class);
我们需要在ViewModelProvider
构造函数中提供ViewModelStoreOwner,并且我了解到hilt无法知道您想要为哪个ViewModelStoreOwner
创建MyViewModel
。
因此,我们将继续以旧方式创建 View 模型,在 Kotlin 中,您将坚持这样做:
@AndroidEntryPoint
abstract class BaseActivity: AppCompatActivity() {
private val viewModel: MyViewModel by viewModels()
}
一旦我发现 Hilt 团队的评论提到了这一点,我就会在这里更新答案。
关于java - 注入(inject)通用 ViewModel Dagger Hilt Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63647420/