While working on a project that uses Dagger 2 for DI, I tried to create a ViewModel
and field inject it even without creating any provider from any module. Biggest confusing moment for me since as far as I know Dagger needs to know how to construct something before using @Inject
.
This is the example Activity and ViewModel class
class MainActivity : DaggerAppCompatActivity(){
@Inject
lateinit var viewModel: MainViewModel
//accessing viewModel methods
}
class MainViewModel @Inject constructor(val sharedPref: SharedPrefManager) : ViewModel() {
//some public methods...
}
Here the sharedPref
was provided using @Provides
inside a module so no question there, but how can this code works and run perfectly with the MainViewModel
? No instantiation at all, no use of ViewModelProvider and Factory. Can someone explain to me what is happening behind the scene?
Note: I could also remove the parameters in the constructor and ended up with this without any problem (I guess).
class MainViewModel @Inject constructor() : ViewModel() {
//some public methods...
}
I am guessing this ViewModel is not aware of the lifecycle as it has no lifecycleOwner