【问题标题】:Where to place logic when extracting data from database in mvvm pattern, using android room?使用android room以mvvm模式从数据库中提取数据时在哪里放置逻辑?
【发布时间】:2019-07-04 10:35:51
【问题描述】:

我正在将旧应用程序重构为 mvvm 模式,使用房间、存储库、视图模型等。

我有一个旧代码,其中包含具有许多功能的内容提供程序辅助类:

    public static int deleteOldLogs(int NumDays) {
    //get NumDays before today, then constract a content provider delete command and run
    ...
    }
or 
public static Cursor getTodayLogs() {
    //get a day from today, then constract a content provider query and run
        ...
    }
or
    public static boolean isActionValid(Context context, int id_order, int id_actionh) {
    //get all products from database table, then check if all products match some criteria, then return boolean result
    ...
    }

我的问题是在哪一层放置这个逻辑?它是应该包含的存储库还是视图模型?我在网上看到的所有例子都很简单,不适合我的目标。

【问题讨论】:

    标签: android mvvm architecture repository android-room


    【解决方案1】:

    视图模型帮助我们在存储库和 UI 之间提供数据。对于与房间数据库的直接交互,我们使用存储库。一旦我们从 repo 中获取数据,我们就可以在 ViewModel 中执行各种计算(即排序、过滤等)。

    为了显示来自数据库的数据,我们使用了一个观察者来观察数据的变化,即 ViewModel 中的 LiveData。

    我们使用 ViewModelProvider 来为我们创建一个 ViewModel。我们需要将我们的 ViewModel 与 ViewModelProvider 连接起来,然后在 onChanged 方法中,我们总是可以获取我们可以在屏幕上显示的更新数据。

    例如。我们想从我们的数据库中获取一些记录。

    为此,我们需要创建一个存储库,该存储库将直接与数据库交互或承载从数据库获取数据的逻辑。

    public class ABCRepository {
    
    @Inject
    DrugsDao mABCDao;
    
    @Inject
    public ABCRepository(){
    
    }
    
    public LiveData<List<NameModel>> getNameByLetter(String letter) {
        return mABCDao.getName(letter);
    }
    }
    

    现在在视图模型中

    public class SearchViewModel extends ViewModel {
    
    @Inject
    ABCRepository mABCRepository;
    
    LiveData<List<GlobalSearchModel>> getNameList(String queryText) {
        MutableLiveData<List<GlobalSearchModel>> mGlobalSearchResults = new 
      MutableLiveData<>();
    
        List<NameModel> synonymsNameList=mABCRepository.getNameByLetter(queryText);
    
       new Thread(() -> {
            List<GlobalSearchModel> globalSearchModelList =         
            mABCRepository.getNameByLetter(queryText)
    
           // this is where you can perform any action on list . either sorting or. 
           filtering and then return the new list to your UI.
    
    
    
            mGlobalSearchResults.postValue(globalSearchModelList);
    
            }).start();
    
    
        return globalSearchModelList;
    }
    
    }
    

    在您的片段或活动中,您可以观察这些数据,

                getViewModel().getAllCountries().observe(this, this::addSearchResultsInRecycler);
    

    希望这会有所帮助。虽然解释得不好,但你可以参考

    https://medium.com/@skydoves/android-mvvm-architecture-components-using-the-movie-database-api-8fbab128d7

    【讨论】:

      猜你喜欢
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      相关资源
      最近更新 更多