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?
AndroidViewModel inherits ViewModel, so it has all the same functionality. The only added functionality for AndroidViewModel is that it is context aware: when initializing AndroidViewModel you have to pass the context as a parameter. This can be used if you want to show toasts for example.
To start an activity, use the method startActivity(intent) . This method is defined on the Context object which Activity extends. The following code demonstrates how you can start another activity via an intent. # Start the activity connect to the # specified class Intent i = new Intent(this, ActivityTwo.
ViewModel : Provides data to the UI and acts as a communication center between the Repository and the UI. Hides the backend from the UI. ViewModel instances survive device configuration changes. LiveData : A data holder class that follows the observer pattern, which means that it can be observed.
AndroidViewModel. Application context aware ViewModel . ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment . It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With