Search code examples
androidviewmodelandroid-architecture-componentsandroid-viewmodel

Android ViewModel and startActivity


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?


Solution

  • 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