Android,我是否使用 ViewModel 执行插入或更新?

标签 android mvvm architecture

我了解 Architecture 组件中的 ViewModel 用于存储和管理数据,因此不会在配置更改期间丢失。

例如,我的 Activity 与 LiveData 或使用存储数据无关。我还应该通过 ViewModel 吗?还是直接实例化Repo Class,调用插入方法?我希望这是有道理的

我使用 ViewModel 的一个例子

public class MainViewModel extends AndroidViewModel {
    private DataRepo dataRepo;
    private LiveData<List<Group>> groupList;
    private LiveData<List<Bill>> billList;

    public MainViewModel(Application application) {
        super(application);
        dataRepo = new DataRepo(this.getApplication));
        groupList = dataRepo.getGroup();
        billList = dataRepo.getBill();
    }

    public LiveData<List<Group>> getGroupList() {
        return groupList:
    }

    public LiveData<List<Bill>> getBillList() {
        return billList:
    }

    public void insertGroupAndMember(Group group) {
        dataRepo.insertGroupAndMember(group);
    }

    public void insertBills(List<Bill> bills) {
        dataRepo.insertBills(bills);
    }

    public List<Member> getMemberList(Group group) {
        return dataRepo.getMembers(group);
    }
}

最佳答案

我认为您想使用 ViewModel 来尽可能保持 UI Controller 的整洁。您的 View 模型应该调用 repo 来执行简单的 CRUD 操作。 见下文snippet来自文档:

Requiring UI controllers to also be responsible for loading data from a database or network adds bloat to the class. Assigning excessive responsibility to UI controllers can result in a single class that tries to handle all of an app's work by itself, instead of delegating work to other classes. Assigning excessive responsibility to the UI controllers in this way also makes testing a lot harder.

关于Android,我是否使用 ViewModel 执行插入或更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53402430/

相关文章:

c# - 如何为多个 BO 属性定义 IDataErrorInfo 错误属性

service - 集中式/分布式/面向服务的架构/应用

java - 仅当使用 Sqlite 数据库选中复选框时,如何将数据添加到另一个表?- android studio

Android 4.0 调试问题 - DDMS 错误?

java - Android java动态设置应用程序权限

wpf - NotifyOnValidationError如何最终调用CanExecute(以及为什么它不适用于MVVM Light RelayCommand)

java - 线程完成时更改布局

c# - 如何在WPF MVVM中将View对象发送到ViewModel?

java - 使用以数据为中心的方法在 Spring MVC 中维护干净的架构

c++ - 关于纯 ECS(实体组件系统)和更新系统的问题