I am trying to follow MVVM design pattern in my android projects, but I faced some problems:
1. I don't know where to put click listeners, put it into the ViewModel or into the view if the action is to transport to another activity/fragment or doing some logic without redirecting to another view
2. I knew that shared preference will be put into the model but create a separate class to all shared preference only or put it into the model class example: in login, I want to save username & password does I make my shared preference functions in UserModel or make a new class and name it SharedPreference ??
Thanks in advance.
Put the on click listeners in your activity/fragment and not in the view-model as listeners are still part of the view.
Shared preference methods should not be called inside the view-model itself, instead, make your view-model call a class that would do the saving of information into the shared preference. In this case, I would recommend using repository pattern. Your view-model will now then call method x() from your repository, and method x() will now then do the saving of information through shared preference, local database or maybe through the cloud.
<Button
android:id="@+id/btn_nw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{() -> viewModel.testLoginModuleClicked()}"
android:text="Login"/>
In ViewModel class
val loginClickEvent = SingleLiveEvent<Void>()
fun testLoginModuleClicked() {
loginClickEvent.call()
}
in your activity/fragment class
loginVM.loginClickEvent.observe(this, Observer {
callMockApi()
})
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