android-jetpack-composeviewmodelandroid-viewmodel

How do I create an instance of a view model with input parameters


I have the following view model which is taking a Context input parameter.

class MyViewModel(val context: Context): ViewModel() {

}

When my app tries to create an instance of this view model, I get an error saying an instance cannot be created. This is clearly because I've not given it the input context parameter, but how do I do this?

val myViewModel: MyViewModel = viewModel()

Solution

  • Disclaimer:

    Please be aware that using a Context in a ViewModel is discouraged.

    Documentation Hint

    Answer:

    You can use an AndroidViewModel for this. It is basically a ViewModel that holds a reference to the Application and thus also to the Context. You can declare it as follows:

    class MyViewModel(application: Application) : AndroidViewModel(application) {
        val someString by mutableStateOf("HELLO")
    
        // below function needs a Context to fetch a String resource
        fun getResourceString(): String {
            return getApplication<Application>().getString(R.string.world)
        }
    }
    

    Then, in your Composable, you can invoke it like this:

    import androidx.lifecycle.viewmodel.compose.viewModel
    
    @Composable
    fun AndroidViewModelSample(myViewModel: MyViewModel = viewModel()) {
        Column {
            Text(text = myViewModel.someString)
            Text(text = myViewModel.getResourceString())
        }
    }
    

    Make sure that you have the needed dependencies added to your build.gradle file:

    implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1'
    

    Output:

    Screenshot