无法从 Android 项目中的不同模块注入 ViewModel

Unable to Inject ViewModel from a different module in Android project

我不确定这是否是 Dagger Hilt 库的限制,但我似乎无法从 activity 中的不同模块注入 ViewModel。

Project:
  :modA (OrderViewModel with @HiltViewModel annotation)
  :modUI (DI stuff here that injects OrderViewModel in Activity) with dependency on modA
  :modOther
@HiltViewModel
class OrderViewModel @Inject constructor(
    private val loadOrdersUseCase: LoadOrdersUseCase,
    private val updateOrderUseCase: UpdateOrderUseCase,
    private val mapper: OrderDataMapper,
) : SharedViewModel<OrderDataModel>() 

注入方式如下:


private val orderViewModel: OrderViewModel by viewModels()

我看不到分别生成的 OrderViewModel_HiltModulesOrderViewModel_HiltModules 类。事实上,当我 运行 应用程序崩溃并出现以下崩溃时,这表明它们的 ViewModel 不在 hilt 应该创建的 ViewModel 键映射中。

Caused by: java.lang.RuntimeException: Cannot create an instance of class com.rowland.delivery.presentation.viewmodels.order.OrderViewModel
.
.
.
Caused by: java.lang.InstantiationException: java.lang.Class<com.rowland.delivery.presentation.viewmodels.order.OrderViewModel> has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)

这是匕首柄的限制吗?任何见解将不胜感激。

有时间复现的朋友可以看看下面的b运行ch代码:

看来编译器是解决这个多模块问题的关键。任何带有任何 Dagger Hilts 属性注释的模块,也需要定义匕首柄依赖项和编译器,即:

    implementation 'com.google.dagger:hilt-android:2.31.2-alpha'
    kapt 'com.google.dagger:hilt-android-compiler:2.31.2-alpha'
    implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
    kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha03'

否则不会生成对应的bindings/providers。在这种情况下,根本就没有生成 ViewModel 提供程序。