Android ViewModel and startActivity
You should call startActivity from activity, not from viewmodel. If you want to open it from viewmodel, you need to create livedata in viewmodel with some navigation parameter and observe on livedata inside the activity.
I like firing Events. :D
As everyone says ViewModel
should not contain Context
or reference to classes that contain Context
. So it is not a good idea to do startActivity
from ViewModel
.
What I would do is have a LiveData containing data for an event. This event will be fired from your ViewModel based on your business logic (Maybe you are showing a CountDown and at the end of it you move to the next Activity?). It is a LiveData
and you can observe on it. Based on the data of this event you can start your activity.
You may want to look at SingleLiveEvent