Context in ViewModel

My class that extends ViewModel() has a private context in it. Is it bad for memoryleaks? I didn’t understand the documentation what they were saying

    > class MaleActivityViewModel : ViewModel() {
    >     private lateinit var mContext: Context
    >     fun getContext(context: Context){
    >           mContext = context
    >    }
    > }

Yes, ViewModels out-live activities. Screen rotation will destroy and recreate activity, but not viewmodel.

Design-wise, whatever you are doing in your viewmodel that requires a context is probably better suited in a different class with responsibilities geared toward whatever that it is. If the context is for UI stuff then that belongs in UI, not ViewModel.

I came across AndroidViewModel to use to get context

Careful with that. It is an application context so config changes or activity specific themes etc will not be properly reflected in that context.

1 Like