Android ViewModel and startActivity

Augusto Carmo picture Augusto Carmo · Feb 21, 2019 · Viewed 9k times · Source

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?

Answer

Alexandr Bahach picture Alexandr Bahach · Feb 21, 2019

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.