I am building an Android App using MVVM and DataBinding. And I have a function inside my ViewModel that starts an Activity. Is it okay to have an onClick call inside a ViewModel
As the principle of MVVM points out that only View (activity/fragment) holds reference to the ViewModel and the ViewModel shouldn't hold reference to any View.
In your case, to start an activity, I will do like this:
MyViewModel.class
public class MyViewModel {
public static final int START_SOME_ACTIVITY = 123;
@Bindable
private int messageId;
public void onClick() {
messageId = START_SOME_ACTIVITY;
notifyPropertyChanged(BR.messageId); //BR class is automatically generated when you rebuild the project
}
public int getMessageId() {
return messageId;
}
public void setMessageId(int message) {
this.messageId = messageId;
}
}
And in your MainActivity.class
@BindingAdapter({"showMessage"})
public static void runMe(View view, int messageId) {
if (messageId == Consts.START_SOME_ACTIVITY) {
view.getContext().startActivity(new Intent(view.getContext(), SomeActivity.class));
}
}
@Override
protected void onPause() {
super.onPause();
finish(); //only call if you want to clear this activity after go to other activity
}
finally, in your activity_main.xml