Search code examples
androidviewmodeldagger-hilt

Inject FragmentComponent dependencies to viewmodel with @ViewModelInject


I want to use my ViewModel inside fragment with FragmentComponent dependencies but I think @ViewModelInject provide ViewModel inside ActivityComponent or ApplicationCoinmponent and cant inject my FragmentComponent dependencies to ViewModel

class XViewModel @ViewModelInject constructor(
    private val xClass: XClass // this dependency provides in FragmentComponent
) : ViewModel() {

}

When I trying to build the project. build failed with KaptException and the hilt compiler say I cant provide XClass. which XClass provide in FragmentComonent. when I move the XClass provider method to ActivityComponent or ApplicationComponent build no more failed with KaptException.

Edit: I read the generated code by Hilt and my guess was right, Hilt and @ViewModelInject Install XViewModel module in ActivityRetainedComponent. I have no idea why?

@Module
@InstallIn(ActivityRetainedComponent.class)
@OriginatingElement(
    topLevelClass = XViewModel.class
)
public interface XViewModel_HiltModule

Solution

  • I found the answer here. hilt team does this because injecting things from the fragment component may leak Fragment instances across configuration changes. ActivityRetainedComponent lives across configuration changes, so it is created at the first onCreate and last onDestroy