android - Unable to Inject ViewModel from a different module in Android project
问题描述
I am not sure if this is a limitation of the Dagger Hilt library, but i seem to be unable to inject a ViewModel from a different module in activity.
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>()
which is injected like:
private val orderViewModel: OrderViewModel by viewModels()
I can't see the respective OrderViewModel_HiltModules
and OrderViewModel_HiltModules
classes generated. In fact, when I ran the app it crashes with crash below, which indicates, their ViewModel is not in the ViewModel keymap that hilt should have created.
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)
Is this a limitation of Dagger Hilt? Any insights would be appreciated.
For anyone who has the time to reproduce it, you can take a look at the following branch of the code:
解决方案
看起来编译器是解决这个多模块问题的关键。使用任何 Dagger Hilts 属性注释的任何模块也需要定义 dagger hilt 依赖项和编译器,即:
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 提供程序。
推荐阅读
- reactjs - TextField 上的 Material-UI 自定义所需文本
- swift - SwiftUI - 缩放、缩放和裁剪图像
- reactjs - React Native View 在 iPhone XR 上被删减
- java - 为什么 curl 在通过 Java 运行时会失败?
- string - Coldfusion - 您可以将字符串视为没有分隔符的列表吗?
- c - 关于 C 编程中的信号
- javascript - 如何从javascript中的电话字符串中删除一组字符?
- grpc - grpc 连接管理的连接数不匹配
- javascript - JavaScript .find 在 Angular Observable 服务中返回未定义
- angular - 错误:调用 saveChanges 时发生未知错误。在 JSDO 中