I am learning ViewModel
and LiveData
and, in the process, a doubt arose.
What should I do if I need to start an Activity
?
Is it ok to pass the context as a parameter to the ViewModel
(the context will not be stored inside the ViewModel)?
ActivityAViewModel : ViewModel() {
// ...
fun openActivityB(context: Context) {
context.startActivity(...)
}
// ...
}
ActivityA {
// ...
fun onSomethingHappened() {
viewModel.openActivityB(this)
}
// ...
}
If not, what is the most correct thing to do in that case?
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.