0

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()
1
  • 1
    Passing a context or other android components directly to a ViewModel is generally discouraged as it can lead to memory leaks. Use AndroidViewModel instead: stackoverflow.com/a/44155403/19212377
    – Megh Lath
    Commented Aug 27, 2024 at 6:02

1 Answer 1

1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.