I'm trying to cut some of Dagger's boilerplate by moving some of my ViewModel instantiation in an abstract base class but can't find quite a good way to do this. My intent is to instantiate all my ViewModels from my base fragment for them to be ready to consume by all child fragments without having them do their own instantiation. My issue lies in retrieving the ViewModel using a generic (VM)- specifically here: .get(viewModel::class.java)
. I also attempted .get(VM::class.java)
that is not permitted
BaseFragment
abstract class BaseFragment<VM : ViewModel> : Fragment() {
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
lateinit var viewModel : VM
override fun onAttach(context: Context?) {
super.onAttach(context)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(viewModel::class.java)
}
}
ViewModelProviders.get(...) method signature
public <T extends ViewModel> T get(@NonNull Class<T> modelClass)
Is this even possible?