注入通用的 ViewModel,使用 Dagger Hilt 在 Android 中。

huangapple go评论84阅读模式
英文:

Inject generic ViewModel Dagger Hilt Android

问题

@AndroidEntryPoint
abstract class BaseActivity<VM: BaseViewModel> : AppCompatActivity() {

@Inject
lateinit var viewModel: VM

}
英文:

Hi I want to inject generic ViewModel type in my BaseActivity, how do i solve that using Dagger Hilt.

@AndroidEntryPoint
 abstract class BaseActivity&lt;VM: BaseViewModel&gt; : AppCompatActivity() {

@Inject
lateinit var viewModel: VM

}

答案1

得分: 2

更新 1

以下是来自 Hilt 团队的回复:

> 因此 @ViewModelInject 有点类似于 @AndroidEntryPoint,是一种单向操作。它只能将 Dagger 依赖项引入到您的类中,但不会将您的 ViewModel 添加到对象图中作为 Dagger 绑定。要想在提供程序或其他地方访问 ViewModel,仍然需要通过正常的 Android API 获取视图模型,就像使用 ViewModelProvider 一样。
>
> 我们无法将其添加到图中的原因在于,我们不知道您想要将 ViewModelStoreOwner 用于哪个情况。

您可以在此处找到此评论。


原始回答

我在几天前尝试过这个,我认为我在互联网上某处读到过这是不可能的(我现在还找不到链接)。

通常在 Java 中,我们会像这样创建 ViewModel:

MyViewModel model = new ViewModelProvider(this).get(MyViewModel.class);

我们需要在 ViewModelProvider 构造函数中提供 ViewModelStoreOwner,而我了解到 Hilt 无法知道您希望为哪个 ViewModelStoreOwner 创建 MyViewModel

因此,我们将继续以旧的方式创建视图模型,在 Kotlin 中,您将继续像这样做:

@AndroidEntryPoint
abstract class BaseActivity: AppCompatActivity() {

    private val viewModel: MyViewModel by viewModels()

}

一旦我找到来自 Hilt 团队的提到此内容的评论,我将在此处更新答案。

英文:

Update 1

Here is the reply I was talking about from Hilt team:

> 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.

You can find this comment here.


Original Answer

I was trying to do this days ago, and I think I read it somewhere on internet that it is not possible for Hilt to do this (I couldn't find the link till now).

Normally in Java we create ViewModel like this:

MyViewModel model = new ViewModelProvider(this).get(MyViewModel.class);

We need to provide ViewModelStoreOwner in ViewModelProvider constructor, and I learned that hilt cannot know which ViewModelStoreOwner you want MyViewModel to be created for.

So we will keep creating view models the old way, and in Kotlin you will stick to do it like this:

@AndroidEntryPoint
abstract class BaseActivity: AppCompatActivity() {

    private val viewModel: MyViewModel by viewModels()

}

Once I find that comment mentioning this from Hilt team, I will update the answer here.

huangapple
  • 本文由 发表于 2020年8月29日 21:21:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63647420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定