Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

dagger 2 - 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:

question from:https://stackoverflow.com/questions/66052391/unable-to-inject-viewmodel-from-a-different-module-in-android-project

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like the compiler are the key to solving this multi-module problem. Any module annotated with any of Dagger Hilts attributes, also needs to have the dagger hilt dependencies and compiler defined i.e:

    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'

Otherwise, the corresponding bindings/providers will not be generated. In this case, the ViewModel providers were simply not generated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...