How to get Context in Android MVVM ViewModel

For Android Architecture Components View Model,

Edit 1 : It’s not a good practice to pass your Activity Context to the Activity’s ViewModel as its a memory leak. You shouldn’t be need your context this way as there are better ways to write your code and there are better ways to manage the reference to your UI as well with AndroidViewModel.

Hence to get the context in your ViewModel, the ViewModel class should extend the Android View Model Class. That way you can get the context as shown in the example code below.

class ActivityViewModel(application: Application) : AndroidViewModel(application) {

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

    //... ViewModel methods 

}

Leave a Comment

tech