无法从Android项目的其他模块注入ViewModel



我不确定这是否是dagger柄库的限制,但我似乎无法从活动的不同模块注入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 keymap中。

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)

这是dagger柄的限制吗?如有任何见地,不胜感激。

对于有时间复制它的人,您可以看看下面的代码分支:

  • https://github.com/RowlandOti/E-CommerceApp-Merchant/tree/refactoring

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

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'

否则,将不会生成相应的绑定/提供程序。在这种情况下,ViewModel提供程序根本没有生成。

最新更新