Dependency Injection in Android With Dagger2 (12)

Centralized Factory for ViewModels

Guowei Lv

1 minute read

It is a bit cumbersome to create a Factory for each ViewModel we have. Actually, we can just create one Factory that is responsible for creating all ViewModels in the app.

The Factory is very straightforward:

class ViewModelFactory @Inject constructor(
        private val myViewModelProvider: Provider<MyViewModel>,
        private val myViewModel2Provider: Provider<MyViewModel2>
): ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return when(modelClass) {
   -> myViewModelProvider.get() as T
   -> myViewModel2Provider.get() as T
            else -> throw RuntimeException("unsupported ViewModel type: $modelClass")

And this is how to use it in activity:

class ViewModelActivity : BaseActivity() {

    @Inject lateinit var myViewModelFactory: ViewModelFactory

    private lateinit var myViewModel: MyViewModel
    private lateinit var myViewModel2: MyViewModel2

    override fun onCreate(savedInstanceState: Bundle?) {


        myViewModel = ViewModelProvider(this, myViewModelFactory).get(
        myViewModel2 = ViewModelProvider(this, myViewModelFactory).get(

comments powered by Disqus