MVVM中允许动作吗?安卓系统 [英] Are actions allowed in MVVM? Android

查看:82
本文介绍了MVVM中允许动作吗?安卓系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果MVVM仅与数据绑定有关,并且不能执行 view.doThis()之类的操作,否则它是MVP,那么如何在视图上调用操作?

If MVVM is all about data binding and cannot do something like view.doThis(), otherwise it's MVP, then how to invoke actions on views?

假设我有一个带有小吃店的视图。 View 由其 ViewModel 控制。这个 ViewModel 应该如何显示 snackbar 而不显示 snackbar.show()

Suppose I have view that has a snackbar. View is controlled by its ViewModel. How is this ViewModel supposed to show snackbar without going snackbar.show()?

推荐答案

在MVVM中,ViewModel捕获视图状态。 View观察ViewModel进行更改并自行更新。因此,View& A之间的通信ViewModel通过更改值来实现(与MVP中的方法调用不同)。

In MVVM, ViewModel captures the state of the view. View observes the ViewModel for changes and updates itself. Thus, the communication between View & ViewModel happens through change of values (as against method calls in MVP).

因为小吃店就像一个全局行为(例如Toast),它可以在活动/片段级别实现。因此,您可以创建一个 MessageHelper 接口,并将其作为依赖项传递给ViewModel。活动将实现它并显示小吃栏

Since Snackbar is like a global behaviour (like Toast), it can be implemented at the Activity/Fragment level. So, you can make a MessageHelper interface and pass it to the ViewModel as a dependency. Activity will implement it and display Snackbar.

示例:

  • ItemViewModel that consumes the interface
  • Activity base class that implements the interface

但是,有些特定于视图的行为无法在活动级别实现。对于这种情况,可以使用 databinding.Observable 来触发事件。例如,假设我们要为特定视图制作动画。我们可以创建一个BindingAdapter

However, its possible that there is some view specific behaviour which cannot be implemented at the Activity level. For such cases, you can make use of databinding.Observable to trigger an event. For example, lets say we want to animate a particular view. We can create a BindingAdapter

@BindingAdapter({"shakeTrigger"})
public static void showSnackbar(View view, Void trigger) {
    // Do the animation here. You could add meaningful argument types to control the animation
}

在XML中,我们可以应用

In XML, we can apply this using

    <TextView
        bind:shakeTrigger="@{vm.shakeTrigger}"/>

然后,在viewModel中,您可以使用数据绑定API触发抖动。使用 BaseObservable 的一种方法可以是:

Then, in the viewModel, you can trigger the shake using Data Binding apis. One way using BaseObservable can be:

public class ConfigurationViewModel extends BaseObservable implements ViewModel {
    @Bindable
    public final Void shakeTrigger = null;

    public void shake() {
        notifyPropertyChanged(BR.shakeTrigger);
    }
}

如果使用RxJava,则触发器可以从 rx.Observable 。您可以检出我的库以将RxJava与Data Binding一起使用。
https://github.com/manas-chaudhari/android-mvvm

If you use RxJava, the trigger could be implemented from rx.Observable. You can checkout my library to use RxJava with Data Binding. https://github.com/manas-chaudhari/android-mvvm

这篇关于MVVM中允许动作吗?安卓系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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