我如何有效地为我的 android 应用程序实施 MVVM 设计模式,这也将简化测试用例的编写?

How do I effectively implement the MVVM design pattern for my android app which will also ease writing of test cases?

我正计划为我的 android 应用实施 MVVM 架构设计模式。我在网上看到它会帮助我实现有效的关注点分离并轻松编写数据模型的测试用例,UI,等等。为此需要一些 insight/advice。

好吧,要了解如何有效地使用 MVVM,请从 Android MVVM Design Pattern Examples

开始

在这里你会发现 post:

I am the developer of Android-Binding. Like @Brentley said, it's a very new project but I do hope to get more buzz and experience so that it can be improved. Back to your question, I have written some simple introduction/tutorials on MVVM with android-binding:

Potential adopters please also register on the project discussion group.

阅读整个主题。您会注意到 MVVM 是一个相对较新的框架,强烈建议与 Google 的 pData Binding library and dependency injection library like Roboguice or Dagger2...

合作使用它

...但最好的是这个:

Approaching Android with MVVM. Building an MVVM architectured application using the Data Binding Library,

作者正在通过示例解释将 MVVM 与数据绑定库结合使用 - 我的意思是他自己创建的应用程序。他总结道:

It’s still too early to know if this approach is the correct way of developing an application, but this experiment has given me a chance to look at one of the possibilities for future projects. It’s something I definitely want to play around with more.

Model-View-ViewModel 很有趣,因为在传统的 Android 架构中,控制器会将数据推送到视图。您会在 Activity 中找到该视图,然后在其上设置内容。

使用 MVVM,您的 ViewModel 会更改一些内容并将更改的内容通知绑定数据框架。然后框架会自动更新绑定到该内容的任何视图。

这两个组件只是通过数据和命令的接口松耦合。

下一个使用 MVVM 的方法确实可以测试。来自 MVVM on Android: What You Need to Know

Because a ViewModel does not depend on the View anymore, you can test a ViewModel without a View even existing. With proper dependency injection for other dependencies, it is very straightforward to test.

For example, instead of binding a VM to a real view, one might create a VM in a test case, give it some data, then call actions on it, to make sure the data is transformed properly. (...) All of this can be done without having to interact with an actual View.

另请阅读:MVVM ON ANDROID USING THE DATA BINDING LIBRARY

希望对您有所帮助