Android ViewModel to Model events

Tyler Hietanen :

I'm working on building a new Android application using Google's Architecture Components (ViewModel, LiveData) using a MVVM architecture.

I'm pretty certain I have most of the flow down already. I understand how the View uses LiveData to observe the ViewModel for changes, and how the ViewModel can similarly observe the Model (in my case, a singleton repository) for changes.

As I'm trying to keep most of my business logic in the model layer, I'd like for the View to 'report' events up to the Model layer where my business logic can decide whether/how to handle the events. Currently, my business logic can update the values in the repository which will propagate the values changes down to the View, but this is only one-directional.

How can I notify the Model of View events?

jeprubio :

The view can not report directly to the model. This goes against the clean architecture and the MVVM.

The ViewModel acts as the liaison between the View and the Model. The ViewModel might take input from the view and place it on the model, or it might interact with a service to retrieve the model, then translate properties and the view will be notified of the changed data through binding or observers.

If you use kotlin (and gradle 2.0 or higher) now you can use listener bindings for event handling and this let you execute directly methods from the ViewModel when events are triggered through lambda expressions. Its then the ViewModel who should be the one which performs the job on the model. When the model is updated the ViewModel gets notified by an observer and the View also reflects the changes with binding.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=385777&siteId=1