Home > Mobile >  Why (Not?) Pass Context to Android ViewModelFactory
Why (Not?) Pass Context to Android ViewModelFactory

Time:03-17

I am refactoring applications that pass "application context" to the view model factory and is accessed in the view model. Is there a definitive opinion if this coding practice is good/ bad/ or OK? For example, I use it to call data repository that loads a data file from the assets directory. If there is a "better practice", where is it documented?

Code snippets

class MainViewModelFactory(private val applicationContext: Context) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
    if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
        return MainViewModel(applicationContext) as T

....

class MainViewModel(
    applicationContext: Context
    ) : ViewModel() {....

    init {
        _dataIsLoaded.value = dataRepository.myFunction(applicationContext, Constants.data_file_name)

CodePudding user response:

It’s perfectly fine as long as the context you store in a ViewModel property truly is the Application Context and not some Activity instance, for some example. You could ensure this by calling applcationContext on it and passing that to the ViewModel constructor in the factory.

If the application Context is your only ViewModel constructor parameter, you should subclass AndroidViewModel and then you don’t even need a factory because the default implicit factory can already handle it.

  • Related