我了解 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/