Android MVVM startActivity的最佳做法 [英] Best practice for Android MVVM startActivity

查看:709
本文介绍了Android MVVM startActivity的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVVM和DataBinding构建一个Android应用程序。我的ViewModel内部有一个启动Activity的函数。
可以在ViewModel中进行onClick调用吗?

I am building an Android App using MVVM and DataBinding. And I have a function inside my ViewModel that starts an Activity. Is it okay to have an onClick call inside a ViewModel?

就像这样。

public class MyViewModel {
    public void onClick(View view, long productId) {
        Context context = view.getContext();
        Intent intent = new Intent(context, ProductDetailActivity.class);
        intent.putExtra("productId", productId);
        context.startActivity(intent);
    }
}

在我的XML中:

...
android:onClick="@{(v) -> viewModel.onClick(v, viewModel.product.id)}">

或者将其移至View并从EventBus或Rx中调用它是一种最佳实践,在我的ViewModel中只有POJO吗?

Or would it be a best practice to move it to the View and call it from EventBus or Rx and have only POJO in my ViewModel?

推荐答案

您的问题的答案是您的目标是什么?

The answer to your question is what is your goal?

如果要使用 MVVM 进行关注分离,以便可以对 Viewmodel ,则应尝试将需要 Context 的所有内容与 Viewmodel 分开。 Viewmodel 包含应用程序的核心业务逻辑,应该没有外部依赖性。

If you want to use MVVM for separation of concerns so that you can unit test your Viewmodel then you should try to keep everything that requires a Context separate from your Viewmodel. The Viewmodel contains the core business logic of your app and should have no external dependencies.

但是我喜欢您在哪里将会进行:)如果打开哪个Activity的决定在View中,那么为它编写JUnit测试非常困难。但是,您可以将对象传递到 Viewmodel 中,该对象执行 startActivity()调用。现在,在您的单元测试中,您可以简单地模拟该对象并验证是否已打开正确的 Activity

However I like where you are going :) If the decision which Activity is opened lies in the View, then it is very very hard to write a JUnit test for it. However you can pass an object into the Viewmodel which performs the startActivity() call. Now in your Unit test you can simply mock this object and verify that the correct Activity is opened

这篇关于Android MVVM startActivity的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆