https://kotlinlang.org logo
#getting-started
Title
# getting-started
n

Nat Strangerweather

12/29/2020, 9:25 PM
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

Dinorah Tovar

12/29/2020, 9:45 PM
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

Nat Strangerweather

12/29/2020, 9:47 PM
Interesting, thanks for this! 🙂👍
d

Dinorah Tovar

12/29/2020, 10:00 PM
For welcome.
n

Nat Strangerweather

12/29/2020, 10:34 PM
@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

Ian Lake

12/29/2020, 11:01 PM
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

Nat Strangerweather

12/30/2020, 6:54 AM
Worked perfectly, thanks!
f

FunkyMuse

01/02/2021, 3:13 PM
@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

Ian Lake

01/02/2021, 4:06 PM
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
6 Views