Home > Enterprise >  Android Kotlin Generic ViewModelFactory
Android Kotlin Generic ViewModelFactory

Time:12-27

I have two classes that inhereit from ViewModelProvider.Factory. The hing is, I have multiple ViewModel and I want to be able to have a generic factory instead of rewriting everything.

My code look like this :


class AViewModelFactory(): ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return AViewModel() as T
    }
}

class BViewModelFactory(): ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return BViewModel() as T
    }
}

class AViewModel: ViewModel() {
    // Some code
}

class BViewModel: ViewModel() {
    // Some code
}

And when using them :

// Fragment A
val factory = AViewModelFactory()
viewModel = ViewModelProvider(this, factory)[AViewModel::class.java]

// Fragment B
val factory = BViewModelFactory()
viewModel = ViewModelProvider(this, factory)[BViewModel::class.java]

Is there a way I could have a generic class (let's say GenericViewModelFactory so I can call it like this :

// Fragment A
val factory = GenericViewModelFactory(AViewModel)
viewModel = ViewModelProvider(this, factory)[AViewModel::class.java]

// Fragment B
val factory = GenericViewModelFactory(BViewModel)
viewModel = ViewModelProvider(this, factory)[BViewModel::class.java]

CodePudding user response:

While your view models doesn't require any dependence you have to use a common factory provided by the framework.

If you need a custom factory in case of provide dependencies or increate instancing speed. You can create a common factory which has the ability to create any of your modes.

class CommonViewModelFactory(): ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        return when(modelClass) {
            AViewModel::class.java -> AViewModel()
            BViewModel::class.java -> BViewModel()
            else -> throw Throwable("Unsupported view model")
        }
    }
}
  • Related