Hi, I am using a View Model to pass some values ba...
# getting-started
n
Hi, I am using a View Model to pass some values based on user clicks. It is working great apart from one thing: my initial default Int in the View Model cannot be 0, because if I use 0, the app resets when I first open it and click on a button. For my initial value I need this code:
Copy code
val notificationManager: NotificationManager =
        context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
But I read that using a context in a View Model is the wrong approach. Is there a solution to this?
d
I do believe that using Context in a ViewModel is not a nice a pattern but, there’s a solution using AndroidViewModel that has a context that will not cause a Memory leak. This may help u
Copy code
class yourViewModel (application: Application) : AndroidViewModel(application) {

    private val context = getApplication<Application>().applicationContext

}
n
Interesting, thanks for this! 🙂👍
d
For welcome.
n
@Dinorah Tovar I'm getting this error: "Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference". I put this in my main page:
Copy code
@Composable
fun MainInterface(viewModel: MainAndroidViewModel = MainAndroidViewModel(application = Application ())) {}
Is it the correct way of initialising it?
i
You should be using
= viewModel()
to get ViewModel instances in Compose (also, feel free to check out #compose): https://developer.android.com/jetpack/compose/interop#viewmodel
🙏 1
n
Worked perfectly, thanks!
f
@Ian Lake if the composable is used in an activity, viewModel() returns the same instance until the activity is finished or the process is killed. Is there a way to scope a viewmodel to a composable? Let's say we take fragments out of the equation, single activity + composables, means every viewmodel that's instantiated will be scoped to the activity lifecycle?
i
There's no ability to scope ViewModels to an arbitrary Composable elements (that's being tracked in https://issuetracker.google.com/issues/165642391), but if you're using Navigation Compose (https://developer.android.com/jetpack/compose/navigation) then ViewModels are automatically scoped to each individual
composable
screen when you use the
viewModel()
API