简体   繁体   English

Android ViewModel 到 Model 事件

[英]Android ViewModel to Model events

I'm working on building a new Android application using Google's Architecture Components (ViewModel, LiveData) using a MVVM architecture.我正在使用 MVVM 架构使用 Google 的架构组件(ViewModel、LiveData)构建一个新的 Android 应用程序。

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.我了解 View 如何使用 LiveData 观察 ViewModel 的变化,以及 ViewModel 如何类似地观察模型(在我的情况下,单例存储库)的变化。

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?如何通知 View 事件的模型?

The view can not report directly to the model.视图不能直接向模型报告。 This goes against the clean architecture and the MVVM.这与干净的架构和 MVVM 背道而驰。

The ViewModel acts as the liaison between the View and the Model. ViewModel 充当 View 和 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. ViewModel 可能从视图获取输入并将其放置在模型上,或者它可能与服务交互以检索模型,然后转换属性,视图将通过绑定或观察者收到更改数据的通知。

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.如果您现在使用 kotlin(和 gradle 2.0 或更高版本),您现在可以使用侦听器绑定进行事件处理,这使您可以在通过 lambda 表达式触发事件时直接从 ViewModel 执行方法。 Its then the ViewModel who should be the one which performs the job on the model.然后 ViewModel 应该是在模型上执行工作的人。 When the model is updated the ViewModel gets notified by an observer and the View also reflects the changes with binding.当模型更新时,观察者会通知 ViewModel,并且 View 也会通过绑定反映更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM