How to get an Instance of ViewModel in activity in 2020/21?

You should update your gradle file to:

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

And due to this change you can pass Activity to the constructor you mentioned:

mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);

Use val viewModel by viewModels<TheViewModel>() in Activities and val viewModel by activityViewModels<TheViewModel>() in fragment to obtain the same viewmodel from the activity (so sharing the viewmodel).

This is part of androidx now


Using Fragment-ktx libr in your app you can get viewModel as below

First Update Gradle File as app -> build.gradle

implementation 'androidx.fragment:fragment-ktx:1.1.0'

// get ViewModel in Activity or Fragment as

private val viewModel: MainActivityViewModel by viewModels()

// If you want to get same instance of ViewModel in ChildFragment as

 private val viewModel: MainActivityViewModel by viewModels(
    ownerProducer = { requireParentFragment() }
)