Best practice for Android MVVM startActivity
The way I do it is, in your ViewModel:
val activityToStart = MutableLiveData<Pair<KClass<*>, Bundle?>>()
This allows you to check the class of Activity started, and the data passed in the Bundle. Then, in your Activity, you can add this code:
viewModel.activityToStart.observe(this, Observer { value ->
val intent = Intent(this, value.first.java)
if(value.second != null)
intent.putExtras(value.second)
startActivity(intent)
})
That's absolutely perfect to put it inside ViewModel
, however you need to set your ViewModel
from Activity
/Fragment
.
Here are some links you can follow to learn MVVM architecture.
Approaching Android with MVVM
Android MVVM
https://github.com/ivacf/archi
People-MVVM
MVVM on Android: What You Need to Know
The answer to your question is what is your goal?
If you want to use MVVM for separation of concerns so that you can unit test your Viewmodel
then you should try to keep everything that requires a Context
separate from your Viewmodel
. The Viewmodel
contains the core business logic of your app and should have no external dependencies.
However I like where you are going :) If the decision which Activity is opened lies in the View, then it is very very hard to write a JUnit test for it. However you can pass an object into the Viewmodel
which performs the startActivity()
call. Now in your Unit test you can simply mock this object and verify that the correct Activity
is opened