Android ViewModel and click listeners

Viewed 6135

Coming from MVP to viewModels, I feel I'm a bit lost when it comes to where to place some code. One example is where to place the click listeners. in MVP I would do something like this

myButton.setOnClickListener { presenter.onMyButtonClicked }

should I be doing the same with a ViewModel? I don't think so. because it means that I'm treating the viewmodel as if it was a presenter.

But, on the other hand, if I handle the click listener in the view (activity or fragment), the view might not end up as dumb as it should be.

Where is the most suitable place in which a click listener should be handled?

2 Answers

The Best Place To add OnClick Listener is View Model when you use MVVM architecture. in MVVM architecture, with data binding, you can handle your on-click listener in many ways.

<Button
  onClick="@{()->viewModel.onMyButtonClicked()}"/>



 <Button 
      onClick="@{(view)->viewModel.onMyButtonClicked(view)}"/>

In this, No need to give Id for each. For doing this first you have to register ViewModel into your activity. in Activity onCreate you have to set the content view as I mentioned below.

ActivityMainBinding activityMainBinding = DataBindingUtils.setContentView(this,R.layout.activity_main);
activityMainBinding.viewModel = MyViewModel(application)
activityMainBinding.lifecycleOwner = this;

after this in your layout file, you have to add ViewModel variable

<layout>
    <data>
        <variable
            name="viewModel"
            type=".MyViewModel" />
    </data>
    ......
    ......
   . .....

<Button
  onClick="@{()->viewModel.onMyButtonClicked()}"/>



 <Button 
      onClick="@{(view)->viewModel.onMyButtonClicked(view)}"/>


</layout>

then If you want to do any changes in Activity, then you have to use Observable variables. that observable variable you have to observe in the activity class. based on the value you have to do the action.

According to the documentation ViewModel is meant to hold Data, and shouldn't hold a reference to anything a Context that might have shorter lifecycle. (Activity, Frag, View, Button etc)

A good codelab here

Not in the codelab, but in the "Intro to ViewModel" Video they recommend usisng a Presenter class to keep the ViewModel simpler if needed.

Related