Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where to put click listeners in mvvm android

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.

like image 898
Muhamed Raafat Avatar asked Mar 27 '18 13:03

Muhamed Raafat


2 Answers

  1. Put the on click listeners in your activity/fragment and not in the view-model as listeners are still part of the view.

  2. 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.

like image 186
Harrison Tiu Avatar answered Sep 17 '22 12:09

Harrison Tiu


   <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()
    })
like image 44
Subham Naik Avatar answered Sep 20 '22 12:09

Subham Naik