google / dagger

A fast dependency injector for Android and Java.
https://dagger.dev
Apache License 2.0
17.45k stars 2.02k forks source link

when should @AndroidEntryPoint be used and why #2682

Closed CROCDC closed 3 years ago

CROCDC commented 3 years ago

the documentation clarifies that : https://dagger.dev/hilt/android-entry-point.html but my question is regarding viewmodels when a fragment needs to be annotated with EntryPoint to access to ViewModel and why

first case: image why this code work?

second case: image why this code does not work

Chang-Eric commented 3 years ago

There is an implicit requirement (I can update the documentation to make it explicit) that for Hilt types to work, they have to be attached to other Hilt types. So an @AndroidEntryPoint Activity has to be attached to an @HiltAndroidApp Application. Same with fragments to activities, etc.

The first case works because even though your view model is used in a non-Hilt fragment, the view model is attaching to the activity which I'm guessing is annotated with @AndroidEntryPoint. So the above requirement is satisfied. In the second case, because you're attaching the view model to the parent fragment which isn't annotated with @AndroidEntryPoint, then you are attaching a Hilt ViewModel to a non-Hilt fragment, so the requirement isn't satisfied.

sirkuryaki commented 3 years ago

Thanks for your answer @Chang-Eric Just to be clear, every Fragment that references a Hilt ViewModel needs to be annotated as @AndroidEntryPoint, am I right?

Chang-Eric commented 3 years ago

Technically just the ones that the ViewModel might use as an owner. Like in the above second case, I think you might get away with only annotating the parent fragment even though the child fragment references the view model (and technically the parent fragment may never reference that view model at all). That might be hard to track though, so I'd personally just put it on all of the fragments if possible.

CROCDC commented 3 years ago

@Chang-Eric what do you think of https://github.com/google/dagger/issues/2912 ???

Chang-Eric commented 3 years ago

@CROCDC The advice @bcorso gave sounds fine to me. He @mentioned me so I saw it and if I took issue with it I would have said something.